如何在Visual Studio中从C#调用PowerShell cmdlet [英] How to call PowerShell cmdlets from C# in Visual Studio

查看:63
本文介绍了如何在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)
}

这能回答您的问题吗?

这篇关于如何在Visual Studio中从C#调用PowerShell cmdlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆