понедельник, 18 августа 2008 г.

How to get PowerShell current runspace from C#

It's possible you faced with situation when you need access to PowerShell current runspace in C# code. For example you need get value of script variable which exists only in runspace of hosting application (i.e. usually poweshell.exe). Of course you can use RunspaceFactory.CreateRunspace(), but the trouble is that new runspace doesn't contain any script variables and added earlier snap-ins.

Here is example how to do this.


Runspace theRunSpace = System.Management.Automation.Runspaces.Runspace.DefaultRunspace;

if (theRunSpace.RunspaceStateInfo.State == RunspaceState.Opened)
{
string theCommand = "$MyScriptVariable";
using (Pipeline thePipeline = theRunSpace.CreateNestedPipeline(theCommand, true))
{
Collection theRetVal = thePipeline.Invoke();
}
}


Note that in shown code CreateNestedPipeline() called instead CreatePipeline(), because at the moment of call CreateNestedPipeline() we stand in executing pipeline already.