我需要从C#中执行PowerShell脚本。该脚本需要命令行参数。
到目前为止,这是我所做的:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.Add(scriptFile); // Execute PowerShell script results = pipeline.Invoke();
scriptFile包含类似“ C:\ Program Files \ MyProgram \ Whatever.ps1”的内容。
该脚本使用命令行参数,例如“ -key Value”,而Value可以是类似路径的内容,也可能包含空格。
我没有这个工作。有谁知道如何从C#中将命令行参数传递给PowerShell脚本并确保空格没有问题?
尝试创建脚本文件作为单独的命令:
Command myCommand = new Command(scriptfile);
然后您可以添加参数
CommandParameter testParam = new CommandParameter("key","value"); myCommand.Parameters.Add(testParam);
最后
pipeline.Commands.Add(myCommand);
这是完整的,已编辑的代码:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); //Here's how you add a new script with arguments Command myCommand = new Command(scriptfile); CommandParameter testParam = new CommandParameter("key","value"); myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand); // Execute PowerShell script results = pipeline.Invoke();