从C#与命令行参数执行PowerShell脚本 [英] Execute PowerShell Script from C# with Commandline Arguments
问题描述
我需要从C#中执行PowerShell脚本。该脚本需要命令行参数。
I need to execute a PowerShell script from within C#. The script needs commandline arguments.
这是我迄今所做的:
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();
脚本文件中包含类似C:\\ Program Files文件\\ MyProgram \\ Whatever.ps1。
scriptFile contains something like "C:\Program Files\MyProgram\Whatever.ps1".
该脚本使用一个命令行参数如 - 键值,而值可以是类似的东西可能还包含空格的路径。
The script uses a commandline argument such as "-key Value" whereas Value can be something like a path that also might contain spaces.
我没有得到这个工作。有谁知道如何命令行参数从C#中传递给PowerShell脚本和确保空格都没有问题?
I don't get this to work. Does anyone know how to pass commandline arguments to a PowerShell script from within C# and make sure that spaces are no problem?
推荐答案
尝试创建脚本文件作为一个单独的命令:
Try creating scriptfile as a separate command:
Command myCommand = new Command(scriptfile);
那么你就可以添加参数
then you can add parameters with
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
最后
pipeline.Commands.Add(myCommand);
下面是完整的,编辑code:的
Here is the complete, edited code:
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();
这篇关于从C#与命令行参数执行PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!