简体   繁体   English

在C#中执行Powershell Cmdlet代码

[英]Executing Powershell Cmdlets Code in C#

How would I use the code used to create powershell cmdlets in another c# method instead of a powershell script. 我如何在另一个c#方法而不是powershell脚本中使用用于创建powershell cmdlet的代码。

I have the following code: 我有以下代码:

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);
    }
}

Don't instantiate the GetCommand class - PowerShell will do that for you! 不要实例化GetCommand类 - PowerShell会为您做到这一点!

First, you'll need to spin up an instance of the PowerShell class to execute your command: 首先,您需要启动PowerShell类的实例来执行命令:

PowerShell ps = PowerShell.Create();

Then add a CommandInfo reference with the AddCommand method: 然后使用AddCommand方法添加CommandInfo引用:

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

And then add your parameter argument: 然后添加参数参数:

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

Now you can execute it (and collect the output) with the Invoke() method: 现在,您可以使用Invoke()方法执行它(并收集输出):

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

Extract the logic in a seperate class and call it directly. 在单独的类中提取逻辑并直接调用它。 Use the cmdlet to be, well, just a shell around this new class. 使用cmdlet就是这个新类的shell。 This Seperation of Concerns (SoC) also enables easier unit tests and leads to an overall cleaner architecture. 这种关注点分离(SoC)还可以实现更轻松的单元测试,从而实现整体更清晰的架构。

Extracted Class Greeter.cs 提取的类Greeter.cs

public class Greeter {
    public Greeter(string name) {
        _Name = name;
    }
    private string _Name;
    public string SayHello() {
        return $"Hello {_Name}";
    }
    public string SayGoodBye() {
        return $"So long {_Name}, and thanks for all the fish!";
    }
}

CommandLet GetGreetingCommand.cs CommandLet GetGreetingCommand.cs

[Cmdlet("Greeting", "Get")]
public class GetGreetingCommand : Cmdlet {
    [Parameter(Mandatory = true)]
    public string Name { get; set; }

    protected override void ProcessRecord() {
        var greeter = new Greeter(Name);
        var greeting = greeter.SayHello();
        WriteObject(greeting);
    }
}

CommandLet GetGoodByeCommand .cs CommandLet GetGoodByeCommand .cs

[Cmdlet("GoodBye", "Get")]
public class GetGoodByeCommand : Cmdlet {
    [Parameter(Mandatory = true)]
    public string Name { get; set; }

    protected override void ProcessRecord() {
        var greeter = new Greeter(Name);
        var goodBye = greeter.SayGoodBye();
        WriteObject(goodBye);
    }
}

Console Main.cs (or any other client-code of Greeter-class) 控制台Main.cs(或Greeter级的任何其他客户端代码)

public static void main(string[] args) {
    var greeter = new Greeter(args.FirstOrDefault());
    Console.WriteLine(greeter.SayHello());
    Console.WriteLine(greeter.SayGoodBye());
}

TestCase 测试用例

public static void SayingHelloUsesName() {
    var sut = new Greeter("Arthur");

    var expected = "Hello Arthur";
    var actual = sut.SayHello();

    Assert.AreEqual(expected, actual);
}

The two concerns here are - the actual BusinessLogic (Greeter.cs) - interoperability with PowerShell, providing mechanisms to parameterize the cmdlet, etc. (Get*Command.cs). 这里的两个问题是 - 实际的BusinessLogic(Greeter.cs) - 与PowerShell的互操作性,提供参数化cmdlet的机制等(Get * Command.cs)。 As you see, the cmdlets really only pass through the calls, while enabling use via PowerShell. 如您所见,cmdlet实际上只通过调用,同时允许通过PowerShell使用。

@Mathias R. Jessen ´ answer could be usefull, if you need to call third party cmdlets, but in most cases, there should be an appropriate (non-powershell) API for what you are trying to do. @Mathias R. Jessen的回答可能很有用,如果你需要调用第三方cmdlet,但在大多数情况下,应该有一个适当的(非powershell)API用于你想要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# 中运行 PowerShell cmdlet - Running PowerShell cmdlets in C# 从C#调用powershell cmdlet - Invoking powershell cmdlets from C# PowerShell Cmdlet的设计模式(在C#中) - Design Patterns for PowerShell Cmdlets (in C#) 在 C# 中创建 PowerShell Cmdlet - 管道链接 - Create PowerShell Cmdlets in C# - Pipeline chaining 在C#中更快地调用PowerShell cmdlet - Invoking PowerShell cmdlets more quickly in C# Powershell cmdlet仅调用一次-C# - Powershell cmdlets invoking Only once - C# 如果我使用 enter/import-pssession cmdlet,为什么在远程计算机(使用参数)上以编程方式 (C#) 执行 powershell cmdlet 不起作用? - Why executing powershell cmdlets programmatically (C#) on remote machine (using arguments) doesn't work if I use enter/import-pssession cmdlets? 用C#代码执行Service Fabric cmdlet - Execute Service fabric cmdlets in c# code 如何获取包含反序列化对象列表的Cmdlet结果的属性(多值属性)(从C#执行Powershell cmdlet) - How to get the properties of Cmdlet results which contain list of deserialized objects (multi-valued properties)(executing powershell cmdlets from c#) 是否可以在c#中的Powershell cmdlet之间共享属性和注释? - Is it possible to share properties and comments between Powershell cmdlets in c#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM