Search code examples
c#powershellpowershell-remoting

Check remote PowerShell session status in C#


I create PowerShell Remoting session per the following code:

AuthenticationMechanism auth = AuthenticationMechanism.Negotiate;

WSManConnectionInfo ci = new WSManConnectionInfo(
    false,
    sRemote,
    5985,
    @"/wsman",
    @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell";,
    creds);
ci.AuthenticationMechanism = auth;

Runspace runspace = RunspaceFactory.CreateRunspace(ci);
runspace.Open();
PowerShell psh = PowerShell.Create();
psh.Runspace = runspace;

I have two questions, based on this code snippet:

  1. I need to run this session over a long time; hence I need to make sure that remote session is alive. How can I do this?
  2. Can I change the duration for which session should be kept alive?

Solution

  • Since you have two questions, I have two headings for separate responses.

    PowerShell Runspace State

    You can examine the state of the PowerShell Runspace object by using the State property, which points to a value of the RunSpaceState .NET enumeration:

    var IsOpened = runspace.RunspaceStateInfo.State == RunspaceState.Opened;
    

    Setting the IdleTimeout

    If you want to set the IdleTimeout for the PowerShell session, then you need to:

    1. Instantiate the PSSessionOption class
    2. Set the IdleTimeout property
    3. Call SetSessionOptions() method on the WSManConnectionInfo object

    Code:

    var option = new PSSessionOption();            // Create the PSSessionOption instance
    option.IdleTimeout = TimeSpan.FromMinutes(60); // Set the IdleTimeout using a TimeSpan object
    ci.SetSessionOptions(option);                  // Set the session options on the WSManConnectionInfo instance