다음을 통해 공유


Cmdlet 내에서 Cmdlet을 호출하는 방법

이 예제에서는 다른 cmdlet 내에서 cmdlet을 호출하는 방법을 보여 주며, 이를 통해 호출된 cmdlet의 기능을 개발 중인 cmdlet에 추가할 수 있습니다. 이 예제에서는 Get-Process cmdlet을 호출하여 로컬 컴퓨터에서 실행 중인 프로세스를 얻습니다. Get-Processcmdlet에 대한 호출은 다음 명령과 동일합니다. 이 명령은 이름이 "a"부터 "t"를 통해 문자로 시작하는 모든 프로세스를 검색합니다.

Get-Process -name [a-t]

중요

System.Management.Automation.Cmdlet 클래스에서 직접 파생되는 cmdlet만 호출할 수 있습니다. System.Management.Automation.PSCmdlet 클래스에서 파생된 cmdlet은 호출할 수 없습니다.

cmdlet 내에서 cmdlet을 호출하려면

  1. 호출할 cmdlet을 정의하는 어셈블리가 참조되고 해당 문이 using 추가되었는지 확인합니다. 이 예제에서는 다음 네임스페이스가 추가됩니다.

    using System.Diagnostics;
    using System.Management.Automation;   // Windows PowerShell assembly.
    using Microsoft.PowerShell.Commands;  // Windows PowerShell assembly.
    
  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());
      }
    }
    

예제

이 예제에서 Get-Process cmdlet은 cmdlet의 System.Management.Automation.Cmdlet.BeginProcessing 메서드 내에서 호출됩니다.

using System;
using System.Diagnostics;
using System.Management.Automation;   // Windows PowerShell assembly.
using Microsoft.PowerShell.Commands;  // Windows PowerShell assembly.

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 { return name; }
      set { name = value; }
    }
    private string name;

    // 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>())
      {
        Console.WriteLine(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 + "!");
    }
  }
}

관련 항목

Writing a Windows PowerShell Cmdlet(Windows PowerShell Cmdlet 작성)