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

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

问题描述:

我正在从Visual Studio创建PowerShell cmdlet,但找不到如何从C#文件中调用cmdlet,或者甚至可以这样做吗?我可以一一运行我的cmdlet没问题,但是我想设置一个cmdlet来在续集中运行多个cmdlet.

I'm creating a PowerShell cmdlets from Visual Studio and I can't find out how to call cmdlets from within my C# file, or if this is even possible? I have no trouble running my cmdlets one by one, but I want to set up a cmdlet to run multiple cmdlets in a sequel.

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

Yes, you can call cmdlets from your C# code.

您将需要以下两个名称空间:

You'll need these two namespaces:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

打开运行空间:

Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();

创建管道:

Pipeline pipeline = runSpace.CreatePipeline();

创建命令:

Command cmd= new Command("APowerShellCommand");

您可以添加参数:

cmd.Parameters.Add("Property", "value");

将其添加到管道中:

pipeline.Commands.Add(cmd);

运行命令:

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

这能回答您的问题吗?