Runspace01 샘플

이 샘플에서는 System.Management.Automation.PowerShell 클래스를 사용하여 Get-Process cmdlet을 동기적으로 실행하는 방법을 보여줍니다. Get-Process cmdlet은 로컬 컴퓨터에서 실행되는 각 프로세스에 System.Diagnostics.Process 개체를 반환합니다. System.Diagnostics.Process.ProcessName*System.Diagnostics.Process.HandleCount* 속성의 값은 반환된 개체에서 추출되어 콘솔 창에 표시됩니다.

요구 사항

이 샘플에는 Windows PowerShell 2.0이 필요합니다.

입증합니다

예시

이 샘플은 Windows PowerShell에서 제공하는 기본 runspace에서 Get-Process cmdlet을 동기적으로 실행합니다.

namespace Microsoft.Samples.PowerShell.Runspaces
{
  using System;
  using System.Management.Automation;
  using PowerShell = System.Management.Automation.PowerShell;

  /// <summary>
  /// This class contains the Main entry point for this host application.
  /// </summary>
  internal class Runspace01
  {
    /// <summary>
    /// This sample uses the PowerShell class to execute
    /// the Get-Process cmdlet synchronously. The name and
    /// handlecount are then extracted from the PSObjects
    /// returned and displayed.
    /// </summary>
    /// <param name="args">Parameter not used.</param>
    /// <remarks>
    /// This sample demonstrates the following:
    /// 1. Creating a PowerShell object to run a command.
    /// 2. Adding a command to the pipeline of the PowerShell object.
    /// 3. Running the command synchronously.
    /// 4. Using PSObject objects to extract properties from the objects
    ///    returned by the command.
    /// </remarks>
    private static void Main(string[] args)
    {
      // Create a PowerShell object. Creating this object takes care of
      // building all of the other data structures needed to run the command.
      using (PowerShell powershell = PowerShell.Create().AddCommand("Get-Process"))
      {
        Console.WriteLine("Process              HandleCount");
        Console.WriteLine("--------------------------------");

        // Invoke the command synchronously and display the
        // ProcessName and HandleCount properties of the
        // objects that are returned.
        foreach (PSObject result in powershell.Invoke())
        {
          Console.WriteLine(
                      "{0,-20} {1}",
                      result.Members["ProcessName"].Value,
                      result.Members["HandleCount"].Value);
        }
      }

      System.Console.WriteLine("Hit any key to exit...");
      System.Console.ReadKey();
    }
  }
}

또한 참조하십시오