使用C#中的参数调用PowerShell脚本

时间:2012-04-21 15:59:23

标签: c# powershell

我有一个存储在文件中的PowerShell脚本。在Windows PowerShell中,我将脚本作为
执行 .\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"

我想从C#调用脚本。目前我正在使用如下的Process.Start,它完美地运作:
Process.Start(POWERSHELL_PATH, string.Format("-File \"{0}\" {1} {2}", SCRIPT_PATH, string.Join(" ", filesToMerge), outputFilename));

我想使用Pipeline类运行它,类似于下面的代码,但我不知道如何传递参数(请记住我没有命名参数,我只是使用$参数)

// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

// create a pipeline and feed it the script text (AddScript method) or use the filePath (Add method)
Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command(SCRIPT_PATH);
command.Parameters.Add("", ""); // I don't have named paremeters
pipeline.Commands.Add(command);

pipeline.Invoke();
runspace.Close();

1 个答案:

答案 0 :(得分:16)

刚刚在另一个问题的评论中找到了它

为了将参数传递给$ args传递null作为参数名称,例如command.Parameters.Add(null, "some value");

该脚本被称为:
.\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"

以下是完整代码:

class OpenXmlPowerTools
{
    static string SCRIPT_PATH = @"..\MergeDocuments.ps1";

    public static void UsingPowerShell(string[] filesToMerge, string outputFilename)
    {
        // create Powershell runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
        runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

        // create a pipeline and feed it the script text
        Pipeline pipeline = runspace.CreatePipeline();
        Command command = new Command(SCRIPT_PATH);
        foreach (var file in filesToMerge)
        {
            command.Parameters.Add(null, file);
        }
        command.Parameters.Add(null, outputFilename);
        pipeline.Commands.Add(command);

        pipeline.Invoke();
        runspace.Close();
    }
}