Runspace01 (C#) コード サンプル

指定したコマンドを実行するコンソール アプリケーションの作成に関するページで説明されている実行 空間のコード サンプルを次に示します。 これを行うには、アプリケーションによって実行空間が呼び出され、コマンドが呼び出されます。 (このアプリケーションでは、実行空間の構成情報は指定されません。また、パイプラインが明示的に作成されるのも同じではありません)。 呼び出されるコマンドは Get-Process コマンドレットです。

注意

microsoft Windows Software Development Kit for Windows Vista および Microsoft .NET Framework .NET Framework 3.0 Runtime Components を使用して、この実行空間の C# ソース ファイル (runspace01.cs) をダウンロードできます。 ダウンロード手順については、「インストール方法」および「Windows PowerShell SDK のダウンロード」をWindows PowerShellしてください。 ダウンロードしたソース ファイルは ディレクトリで使用 <PowerShell Samples> できます。

コード サンプル

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();
    }
  }
}

参照

Windows PowerShell プログラマー ガイド

Windows PowerShell SDK