简体   繁体   中英

How to get powershell runspace status in c#

I'm working with Powershell runspaces in ASP.Net MVC and finding it difficult to get documentation on how to check the status of an existing Powershell Runspace. Really appreciate any insight!

Controller

public class DemoController : ApiController
{
    PowerShell psInstance = PowerShell.Create();
    static Runspace rSpace = RunspaceFactory.CreateRunspace();

...

private void Initialise()
    {
        try
        {
            psInstance.Runspace = rSpace;
            if (HOW TO CHECK IF RUNSPACE IS ALREADY OPEN?) <<-- 
            {
                DO NOTHING
            }
                else 
            {
                rSpace.Open();
                LoadModules();
            }
        }
        catch (CmdletInvocationException e)
        {
            rSpace.Close();
            rSpace.Dispose();
            psInstance.Dispose();
            throw e;
        }
    }

Inspect the RunspaceStateInfo property

if(rSpace.RunspaceStateInfo.State == RunspaceState.Opened)
{
    // runspace is open, do stuff
}
else if(rSpace.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
{
    // call rSpace.Open() before invocation
}
else 
{
    // runspace state is either broken, already in use or closed
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM