我如何使用在另一个 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/