How to call PowerShell cmdlets from C# in Visual Studio

别等时光非礼了梦想. 提交于 2019-11-28 05:05:36

问题


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.


回答1:


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

You'll need these two namespaces:

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

Open a runspace:

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

Create a pipeline:

Pipeline pipeline = runSpace.CreatePipeline();

Create a command:

Command cmd= new Command("APowerShellCommand");

You can add parameters:

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

Add it to the pipeline:

pipeline.Commands.Add(cmd);

Run the command(s):

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

Does this answer your question?



来源:https://stackoverflow.com/questions/21264112/how-to-call-powershell-cmdlets-from-c-sharp-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!