[英]Invoking PowerShell Script with Arguments from C#
I have a PowerShell script stored in a file. 我有一个存储在文件中的PowerShell脚本。 In Windows PowerShell, I execute the script as 在Windows PowerShell中,我执行脚本为
.\\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"
I want to call the script from C#. 我想从C#调用脚本。 Currently I am using Process.Start as follows which works perfectly: 目前我使用Process.Start如下工作:
Process.Start(POWERSHELL_PATH, string.Format("-File \\"{0}\\" {1} {2}", SCRIPT_PATH, string.Join(" ", filesToMerge), outputFilename));
I want to run it using Pipeline
class, something like the below code but I don't know how to pass the arguments (keep in mind that I don't have named arguments, I am just using $args) 我想使用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();
Just found it in one of the comments to another question 刚刚在另一个问题的评论中找到了它
In order to pass arguments to the $args pass null as the parameter name, eg command.Parameters.Add(null, "some value");
为了将参数传递给$ args传递null作为参数名,例如command.Parameters.Add(null, "some value");
The script is called as: 该脚本被称为:
.\\MergeDocuments.ps1 "1.docx" "2.docx" "merge.docx"
Here is the full code: 这是完整的代码:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.