共用方式為


如何從 Cmdlet 叫用 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

  1. 請確定會參考定義要叫用之 Cmdlet 的元件,並加入適當的 using 語句。 在此範例中,會新增下列命名空間。

    using System.Diagnostics;
    using System.Management.Automation;   // PowerShell assembly.
    using Microsoft.PowerShell.Commands;  // PowerShell cmdlets assembly you want to call.
    
  2. 在 Cmdlet 的輸入處理方法中,建立要叫用之 Cmdlet 的新實例。 在此範例中,會建立類型為 Microsoft.PowerShell.Commands.GetProcessCommand 的物件,以及包含叫用 Cmdlet 時所使用的自變數的字符串。

    GetProcessCommand gp = new GetProcessCommand();
    gp.Name = new string[] { "[a-t]*" };
    
  3. 呼叫 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 + "!");
    }
  }
}

另請參閱

撰寫 Windows PowerShell Cmdlet