InitialSessionState を作成する

PowerShell コマンドは、実行空間で実行されます。 アプリケーションで PowerShell をホストするには 、System.Management.Automation.Runspaces.Runspace オブジェクトを作成する必要 があります。 すべての実行空間には 、System.Management.Automation.Runspaces.InitialSessionState オブジェクト が関連付けされています。 InitialSessionState は、その実行空間で使用できるコマンド、変数、モジュールなど、実行空間の特性を指定します。

既定の InitialSessionState を作成する

InitialSessionState クラスの CreateDefaultメソッドと CreateDefault2メソッドを使用して 、InitialSessionState オブジェクトを作成 できます。 CreateDefault メソッドは、すべての組み込みコマンドを読み込んだ InitialSessionState を作成します。一方、CreateDefault2 メソッドでは、PowerShell をホストするために必要なコマンド (Microsoft.PowerShell.Core モジュールのコマンド) のみを読み込まれます。

ホスト アプリケーションで使用できるコマンドをさらに制限する場合は、制約付き実行空間を作成する必要があります。 詳細については、「制約付き 実行空間の作成」を参照してください

次のコードは 、InitialSessionState を作成し、それを実行空間に割り当て、その実行空間内のパイプラインにコマンドを追加して、コマンドを呼び出す方法を示しています。 コマンドの追加と呼び出しの詳細については、「コマンドの追加と呼び出し 」を参照してください

namespace SampleHost
{
  using System;
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;

  class HostP4b
  {
    static void Main(string[] args)
    {
      // Call the InitialSessionState.CreateDefault method to create
      // an empty InitialSessionState object, and then add the
      // elements that will be available when the runspace is opened.
      InitialSessionState iss = InitialSessionState.CreateDefault();
      SessionStateVariableEntry var1 = new
          SessionStateVariableEntry("test1",
                                    "MyVar1",
                                    "Initial session state MyVar1 test");
      iss.Variables.Add(var1);

      SessionStateVariableEntry var2 = new
          SessionStateVariableEntry("test2",
                                    "MyVar2",
                                    "Initial session state MyVar2 test");
      iss.Variables.Add(var2);

      // Call the RunspaceFactory.CreateRunspace(InitialSessionState)
      // method to create the runspace where the pipeline is run.
      Runspace rs = RunspaceFactory.CreateRunspace(iss);
      rs.Open();

      // Call the PowerShell.Create() method to create the PowerShell object,
      // and then specify the runspace and commands to the pipeline.
      // and create the command pipeline.
      PowerShell ps = PowerShell.Create();
      ps.Runspace = rs;
      ps.AddCommand("Get-Variable");
      ps.AddArgument("test*");

      Console.WriteLine("Variable             Value");
      Console.WriteLine("--------------------------");

      // Call the PowerShell.Invoke() method to run
      // the pipeline synchronously.
      foreach (PSObject result in ps.Invoke())
      {
        Console.WriteLine("{0,-20}{1}",
            result.Members["Name"].Value,
            result.Members["Value"].Value);
      } // End foreach.

      // Close the runspace to free resources.
      rs.Close();

    } // End Main.
  } // End SampleHost.
}

参照

制約付き実行空間を作成する

コマンドを追加し、呼び出す