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

时间:2018-03-02 07:35:53

标签: c# powershell

我最近开始学习PowerShell和C#。我想在带有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();

        }
    }
}

但是,我找不到在管道中添加参数脚本的方法

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

如果单独创建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()