简体   繁体   English

Powershell 和 C#:在管道中添加参数脚本

[英]Powershell and C# : add a parameter script in a pipeline

I started learning PowerShell and C# recently.我最近开始学习 PowerShell 和 C#。 I would like to use it in a web app with visual studio.我想在带有 Visual Studio 的网络应用程序中使用它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;


namespace Extraction_test.Controllers
{
    public class HomeController : Controller
    {
               public string Index() //PowershellExtract()
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(@"$filepath=""C:\Users\myusernamefolder\Downloads\ReadExcel\Test.xlsx"";");
            pipeline.Commands.Add("Param([string]$filepath;)");
            string scriptpath = "[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo] \"en-US\";" +
                    "$Excel = New-Object -ComObject Excel.application;" +
                    "$Excel.visible=$True;" +
                    "$Workbook=$Excel.Workbooks.open($filepath);" +
                    "$Worksheet=$WorkbookSheets.item(\"Feuil1\");" +
                    "$Worksheet.activate();" +
                    "$col = 4;" +
                    "$lines = @(5,6,7,9);" +
                    "foreach ($line in $lines) { $global:output = $Worksheet.Cells.Item($line,$col).Value(); }" +
                    "$global:test='test string value'; " +
                    "$workbook.Close();" +
                    "$Excel.Quit();";
            pipeline.Commands.AddScript(scriptpath);
            Collection<PSObject> results = pipeline.Invoke();
            var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
            //var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
            return result.ToString();

        }
    }
}

However, I couldn't find anywhere a way to add a parameter script in a pipeline但是,我在任何地方都找不到在管道中添加参数脚本的方法

pipeline.Commands.Add("Param([string]$filepath;)");

Thanks in advance!提前致谢!

if you create the Command object separately, you can add a CommandParameter to it:如果单独创建 Command 对象,则可以向其添加 CommandParameter:

Pipeline pipeline = runspace.CreatePipeline();    
string scriptFile = Path.Combine(ScriptDir, scriptpath);
Command scriptCommand = new Command(scriptFile);

CommandParameter commandParm = new CommandParameter("name", "value");
scriptCommand.Parameters.Add(commandParm);
pipeline.Commands.Add(scriptCommand);
pipeline.Invoke()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM