![](/img/trans.png)
[英]How to access module's privatedata from a binary PowerShell Cmdlet?
[英]How to call PowerShell Cmdlet from a binary (C#) module?
如果可以引用實現cmdlet的類,則可以通過創建類的實例來“調用”cmdlet,設置表示參數的任何屬性並調用Cmdlet.Invoke<T>()
方法。 這是一個例子:
using System.Linq;
using System.Management.Automation;
namespace MyModule.Commands
{
[Cmdlet(VerbsLifecycle.Invoke, "AnotherCmdlet")]
public class InvokeAnotherCmdlet : Cmdlet
{
[Parameter(Mandatory = true)]
public string Username { get; set; }
protected override void ProcessRecord()
{
GetADUserCommand anotherCmdlet = new GetADUserCommand() {
// Pass CommandRuntime of calling cmdlet to the called cmdlet (note 1)
CommandRuntime = this.CommandRuntime,
// Set parameters
Username = this.Username
};
// Cmdlet code isn't ran until the resulting IEnumerable is enumerated (note 2)
anotherCmdlet.Invoke<object>().ToArray();
}
}
[Cmdlet(VerbsCommon.Get, "ADUser")]
public class GetADUserCommand : Cmdlet
{
[Parameter(Mandatory = true)]
public string Username { get; set; }
protected override void ProcessRecord()
{
WriteVerbose($"Getting AD User '{Username}'");
}
}
}
有幾點需要注意:
Cmdlet.CommandRuntime
屬性的值傳遞給調用的Cmdlet對象。 這將確保,如果被調用的cmdlet寫入對象流(例如,通過調用WriteObject
),那些對象將進入主機。 另一種方法是調用cmdlet枚舉在調用cmdlet上調用Invoke<T>()
方法的結果。 Invoke<T>()
方法不會立即調用cmdlet,因為方法名稱可能會建議。 它改為返回一個IEnumberable<T>
對象。 枚舉對象將調用該命令。 您是對的,正確的方法是創建PowerShell
的實例。 強類型方法是
PowerShell ps = PowerShell.Create();
ps.AddCommand(new CmdletInfo("Get-Cmdlet", typeof(GetCmdletCommand)));
雖然從 C# 調用 PowerShell 有其優點,但如果您想這樣做,您可能應該重新考慮您的方法,因為您可能遵循了一種反模式。 通過將一個 cmdlet 的輸出與另一個的輸入進行匹配並在管道中調用它們來使您的 cmdlet“適合”在一起會更明智。 另一個問題的更好答案描述了粘在一起的 cmdlet“單元”的設計選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.