如何在Visual Studio中从C#调用PowerShell cmdlet

Bjo*_*orn 3 c# powershell cmdlets visual-studio-2012

我正在从Visual Studio创建一个PowerShell cmdlet,我无法找到如何从我的C#文件中调用cmdlet,或者这是否可能?我一个接一个地运行我的cmdlet没有问题,但我想设置一个cmdlet来在续集中运行多个cmdlet.

tnw*_*tnw 7

是的,您可以从C#代码中调用cmdlet.

您将需要这两个名称空间:

using System.Management.Automation;
using System.Management.Automation.Runspaces;
Run Code Online (Sandbox Code Playgroud)

打开一个运行空间:

Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
Run Code Online (Sandbox Code Playgroud)

创建一个管道:

Pipeline pipeline = runSpace.CreatePipeline();
Run Code Online (Sandbox Code Playgroud)

创建一个命令:

Command cmd= new Command("APowerShellCommand");
Run Code Online (Sandbox Code Playgroud)

您可以添加参数:

cmd.Parameters.Add("Property", "value");
Run Code Online (Sandbox Code Playgroud)

将其添加到管道:

pipeline.Commands.Add(cmd);
Run Code Online (Sandbox Code Playgroud)

运行命令:

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
   ....do stuff with psObject (output to console, etc)
}
Run Code Online (Sandbox Code Playgroud)

这回答了你的问题了吗?