执行PowerShell脚本

执行PowerShell脚本

本文介绍了使用命令行参数从C#执行PowerShell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从C#中执行PowerShell脚本。该脚本需要命令行参数。

I need to execute a PowerShell script from within C#. The script needs commandline arguments.

这是我到目前为止所做的:

This is what I have done so far:

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的内容。

scriptFile contains something like "C:\Program Files\MyProgram\Whatever.ps1".

脚本使用命令行参数,例如-key Value,而Value可以是类似于也可能包含空格的路径。

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);

然后您可以使用

CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);

最后

pipeline.Commands.Add(myCommand);






,编辑后的代码:


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脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:26