Creating an InitialSessionState

PowerShell commands run in a runspace. To host PowerShell in your application, you must create a System.Management.Automation.Runspaces.Runspace object. Every runspace has a System.Management.Automation.Runspaces.InitialSessionState object associated with it. The InitialSessionState specifies characteristics of the runspace, such as which commands, variables, and modules are available for that runspace.

Create a default InitialSessionState

The CreateDefault and CreateDefault2 methods of the InitialSessionState class can be used to create an InitialSessionState object. The CreateDefault method creates an InitialSessionState with all of the built-in commands loaded, while the CreateDefault2 method loads only the commands required to host PowerShell (the commands from the Microsoft.PowerShell.Core module).

If you want to further limit the commands available in your host application you need to create a constrained runspace. For information, see Creating a constrained runspace.

The following code shows how to create an InitialSessionState, assign it to a runspace, add commands to the pipeline in that runspace, and invoke the commands. For more information about adding and invoking commands, see Adding and invoking commands.

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

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

      SessionStateVariableEntry var2 = 
        new SessionStateVariableEntry("test2",
                                      "Initial session state MyVar2 test");

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

      // Call PowerShell.Create() to create the PowerShell object, then 
      // specify the runspace and pipeline commands.
      PowerShell ps = PowerShell.Create();
      ps.Runspace = rs;

      Console.WriteLine("Variable             Value");

      // Call ps.Invoke() to run the pipeline synchronously.
      foreach (PSObject result in ps.Invoke())
      } // End foreach.

      // Close the runspace to free resources.

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

See Also

Creating a constrained runspace

Adding and invoking commands