此示例演示如何调用从另一个二进制 cmdlet 中直接派生自 [System.Management.Automation.Cmdlet]
的二进制 cmdlet 的二进制 cmdlet,这样就可以将调用的 cmdlet 的功能添加到正在开发的二进制 cmdlet。 在此示例中,将调用 Get-Process
cmdlet 以获取在本地计算机上运行的进程。 对 Get-Process
cmdlet 的调用等效于以下命令。 此命令检索名称以字符“a”开头到“t”的所有进程。
Get-Process -Name [a-t]*
重要
只能调用直接从 System.Management.Automation.Cmdlet 类派生的 cmdlet。 无法调用派生自 System.Management.Automation.PSCmdlet 类的 cmdlet。 有关示例,请参阅 如何在 PSCmdlet中调用 PSCmdlet。
从 cmdlet 中调用 cmdlet
确保引用定义要调用的 cmdlet 的程序集,并添加相应的
using
语句。 在此示例中,将添加以下命名空间。using System.Diagnostics; using System.Management.Automation; // PowerShell assembly. using Microsoft.PowerShell.Commands; // PowerShell cmdlets assembly you want to call.
在 cmdlet 的输入处理方法中,创建要调用的 cmdlet 的新实例。 在此示例中,Microsoft.PowerShell.Commands.GetProcessCommand 类型的对象与包含调用 cmdlet 时使用的参数的字符串一起创建。
GetProcessCommand gp = new GetProcessCommand(); gp.Name = new string[] { "[a-t]*" };
调用 System.Management.Automation.Cmdlet.Invoke* 方法来调用
Get-Process
cmdlet。foreach (Process p in gp.Invoke<Process>()) { Console.WriteLine(p.ToString()); } }
示例
在此示例中,从 cmdlet 的 System.Management.Automation.Cmdlet.BeginProcessing 方法中调用 Get-Process
cmdlet。
using System;
using System.Diagnostics;
using System.Management.Automation; // PowerShell assembly.
using Microsoft.PowerShell.Commands; // PowerShell cmdlets assembly you want to call.
namespace SendGreeting
{
// Declare the class as a cmdlet and specify an
// appropriate verb and noun for the cmdlet name.
[Cmdlet(VerbsCommunications.Send, "GreetingInvoke")]
public class SendGreetingInvokeCommand : Cmdlet
{
// Declare the parameters for the cmdlet.
[Parameter(Mandatory = true)]
public string Name { get; set; }
// Override the BeginProcessing method to invoke
// the Get-Process cmdlet.
protected override void BeginProcessing()
{
GetProcessCommand gp = new GetProcessCommand();
gp.Name = new string[] { "[a-t]*" };
foreach (Process p in gp.Invoke<Process>())
{
WriteVerbose(p.ToString());
}
}
// Override the ProcessRecord method to process
// the supplied user name and write out a
// greeting to the user by calling the WriteObject
// method.
protected override void ProcessRecord()
{
WriteObject("Hello " + Name + "!");
}
}
}