PowerShell using an existing session state to fill in InitialSessionState

c#, powershell

Solution

Session state definitely can't be shared across runspaces, it holds session specific data like variables.

The InitialSessionState that was used to create a runspace is a property of the runspace. You can access the current runspace via thread local storage using the Runspace.DefaultRunspace property: http://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.runspace.defaultrunspace(v=vs.85).aspx

That said, you may want to look at RunspacePool - the pool of runspaces will all be created from the same InitialSessionState. This way you avoid creating more runspaces than necessary, instead just reusing a runspace from the pool.

Problem

I am trying to call\create runspace within a class that derived from PSCmdlet. Since PSCmdlet includes a default session state that contains shared data I want to reuse in the runspace, I am wondering if there is a programmatically way to convert the current sessionState into the runspace's InitialSessionState ? If there is no such way, I am not really understand why such session state info cannot be shared within different runspace. This looks like running a remote runspace to me. Can anyone explain? For example, ``` namespace CustomCmdlet.Test { [Cmdlet("Get", "Test1")] public class GetTest1 : PSCmdlet { protected override void ProcessRecord() { WriteObject("1"); } } [Cmdlet("Get", "Test2")] public class GetTest2 : PSCmdlet { protected override void ProcessRecord() { // instead of import the module dll using Runspace // InitialSessionState.ImportModule(new string[] {"CustomCmdlet.Test.dll"}); // Runspace runspace = RunspaceFactory.CreateRunspace(InitialSessionState) // is it any way to import the PSCmdlet.SessionState into the InitialSessionState? } } ``` We are using PowerShell 4.0, if this is relevant.

Original source