다음을 통해 공유


명령 추가 및 호출

Runspace를 만든 후 파이프라인에 Windows PowerShell 명령 및 스크립트를 추가한 다음 파이프라인을 동기적으로 또는 비동기적으로 호출할 수 있습니다.

파이프라인 만들기

System.Management.Automation.PowerShell 클래스는 파이프라인에 명령, 매개 변수 및 스크립트를 추가하는 몇 가지 메서드를 제공합니다. System.Management.Automation.PowerShell.Invoke* 메서드의 오버로드를 호출하거나 System.Management.Automation.PowerShell.BeginInvoke* 오버로드를 호출한 다음 system.Management.Automation.PowerShell.EndInvoke* 메서드의 오버로드를 호출하여 파이프라인을 동기적으로 호출할 수 있습니다.

AddCommand

  1. System.Management.Automation.PowerShell 개체를 만듭니다.

    PowerShell ps = PowerShell.Create();
    
  2. 실행할 명령을 추가합니다.

    ps.AddCommand("Get-Process");
    
  3. 명령을 호출합니다.

    ps.Invoke();
    

System.Management.Automation.PowerShell.Invoke* 메서드를 호출하기 전에 System.Management.Automation.PowerShell.AddCommand* 메서드를 두 번 이상 호출하는 경우 첫 번째 명령의 결과가 두 번째 명령으로 파이프되는 등입니다. 이전 명령의 결과를 명령에 파이프하지 않으려면 대신 System.Management.Automation.PowerShell.AddStatement* 호출하여 추가합니다.

AddParameter

이전 예제에서는 매개 변수 없이 단일 명령을 실행합니다. System.Management.Automation.PSCommand.AddParameter* 메서드를 사용하여 명령에 매개 변수를 추가할 수 있습니다. 예를 들어 다음 코드는 컴퓨터에서 실행되는 powershell 명명된 모든 프로세스 목록을 가져옵니다.

PowerShell.Create().AddCommand("Get-Process")
                   .AddParameter("Name", "powershell")
                   .Invoke();

System.Management.Automation.PSCommand.AddParameter* 반복적으로 호출하여 매개 변수를 추가할 수 있습니다.

PowerShell.Create().AddCommand("Get-Command")
                   .AddParameter("Name", "Get-VM")
                   .AddParameter("Module", "Hyper-V")
                   .Invoke();

system.Management.Automation.PowerShell.AddParameters* 메서드를 호출하여 매개 변수 이름 및 값의 사전을 추가할 수도 있습니다.

IDictionary parameters = new Dictionary<String, String>();
parameters.Add("Name", "Get-VM");

parameters.Add("Module", "Hyper-V");
PowerShell.Create().AddCommand("Get-Command")
   .AddParameters(parameters)
      .Invoke()

AddStatement

파이프라인의 끝에 추가 문을 추가하는 System.Management.Automation.PowerShell.AddStatement* 메서드를 사용하여 일괄 처리를 시뮬레이션할 수 있습니다. 다음 코드는 powershell이름의 실행 중인 프로세스 목록을 가져오고 실행 중인 서비스 목록을 가져옵니다.

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process").AddParameter("Name", "powershell");
ps.AddStatement().AddCommand("Get-Service");
ps.Invoke();

AddScript

System.Management.Automation.PowerShell.AddScript* 메서드를 호출하여 기존 스크립트를 실행할 수 있습니다. 다음 예제에서는 파이프라인에 스크립트를 추가하고 실행합니다. 이 예제에서는 D:\PSScripts폴더에 MyScript.ps1이라는 스크립트가 이미 있다고 가정합니다.

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();

또한 useLocalScope부울 매개 변수를 사용하는 System.Management.Automation.PowerShell.AddScript* 메서드 버전도 있습니다. 이 매개 변수가 true설정되면 스크립트가 로컬 범위에서 실행됩니다. 다음 코드는 로컬 범위에서 스크립트를 실행합니다.

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1"), true).Invoke();

파이프라인을 동기적으로 호출

파이프라인에 요소를 추가한 후 호출합니다. 파이프라인을 동기적으로 호출하려면 System.Management.Automation.PowerShell.Invoke* 메서드의 오버로드를 호출합니다. 다음 예제에서는 파이프라인을 동기적으로 호출하는 방법을 보여줍니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;

namespace HostPS1e
{
  class HostPS1e
  {
    static void Main(string[] args)
    {
      // Using the PowerShell.Create and AddCommand
      // methods, create a command pipeline.
      PowerShell ps = PowerShell.Create().AddCommand ("Sort-Object");

      // Using the PowerShell.Invoke method, run the command
      // pipeline using the supplied input.
      foreach (PSObject result in ps.Invoke(new int[] { 3, 1, 6, 2, 5, 4 }))
      {
          Console.WriteLine("{0}", result);
      } // End foreach.
    } // End Main.
  } // End HostPS1e.
}

파이프라인을 비동기적으로 호출

System.Management.Automation.PowerShell.BeginInvoke* 오버로드를 호출하여 IAsyncResult 개체를 만든 다음 System.Management.Automation.PowerShell.EndInvoke* 메서드를 호출하여 파이프라인을 비동기적으로 호출합니다.

다음 예제에서는 파이프라인을 비동기적으로 호출하는 방법을 보여줍니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;

namespace HostPS3
{
  class HostPS3
  {
    static void Main(string[] args)
    {
      // Use the PowerShell.Create and PowerShell.AddCommand
      // methods to create a command pipeline that includes
      // Get-Process cmdlet. Do not include spaces immediately
      // before or after the cmdlet name as that will cause
      // the command to fail.
      PowerShell ps = PowerShell.Create().AddCommand("Get-Process");

      // Create an IAsyncResult object and call the
      // BeginInvoke method to start running the
      // command pipeline asynchronously.
      IAsyncResult asyncpl = ps.BeginInvoke();

      // Using the PowerShell.Invoke method, run the command
      // pipeline using the default runspace.
      foreach (PSObject result in ps.EndInvoke(asyncpl))
      {
        Console.WriteLine("{0,-20}{1}",
                result.Members["ProcessName"].Value,
                result.Members["Id"].Value);
      } // End foreach.
      System.Console.WriteLine("Hit any key to exit.");
      System.Console.ReadKey();
    } // End Main.
  } // End HostPS3.
}

또한 참조하십시오

InitialSessionState 만들기

제한된 runspace 만들기