使用命令行参数从C#执行PowerShell脚本

我需要从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();

以上是 使用命令行参数从C#执行PowerShell脚本 的全部内容, 来源链接: utcz.com/qa/426457.html

回到顶部