我有一个存储在文件中的 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
类来运行它,类似于下面的代码,但我不知道如何传递参数(请记住,我没有命名参数,我只是使用 $args)
// 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();