c# - 在 C# 中执行 Powershell Cmdlet 代码

标签 c# powershell

我如何使用在另一个 C# 方法中创建 powershell cmdlet 的代码而不是 powershell 脚本。

我有以下代码:

public class Program
{
    static void Main(string[] args)
    {
        var getCommand = new GetCommand { Text = "Hello World"};

        //help needed here
    }
}

[Cmdlet("Test", "Get")]
public class GetCommand : Cmdlet
{
    [Parameter(Mandatory = true)]
    public string Text { get; set; }

    protected override void ProcessRecord()
    {
        WriteObject(Text);
    }
}

最佳答案

不要实例化 GetCommand 类 - PowerShell 会为您执行此操作!

首先,您需要启动 PowerShell 类的实例来执行命令:

PowerShell ps = PowerShell.Create();

然后使用 AddCommand 方法添加 CommandInfo 引用:

ps.AddCommand(new CmdletInfo("Test-Get", typeof(GetCommand)));

然后添加您的参数参数:

ps.AddParameter("Text", "Hello World");

现在您可以使用 Invoke() 方法执行它(并收集输出):

var output = ps.Invoke();
foreach(var obj in ouput)
{
    Console.WriteLine("Output was: {0}", obj);
}

关于c# - 在 C# 中执行 Powershell Cmdlet 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43589492/

相关文章:

parsing - 从 dhcp 输出作为单行输出

Powershell - 提示输入要添加到命令的变量

multithreading - 在Powershell中使用system.thread.threadpool

java - 如何使用java实现aiml

c# - 自定义字符串格式,数字到时间

windows - Docker 在 Windows 容器上的健康检查和退出代码 ("||"linux 等效)

c# - 这是从 C# 使用 PowerShell 打印 'Hello World' 的最简单方法吗?

c# - 使用性能计数器监视特定端口

c# - 从 ADUser 获取 UserPrincipal

c# - 处理从 CSV 导入的引号