在C#中检查远程PowerShell会话状态

时间:2014-01-18 22:15:49

标签: c# powershell powershell-remoting

我按照以下代码创建PowerShell Remoting会话:

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;

我有两个问题,基于此代码段:

  1. 我需要长时间运行这个会话;因此我需要确保远程会话是活着的。我怎么能这样做?
  2. 我可以更改会话应该保持活动的持续时间吗?

1 个答案:

答案 0 :(得分:3)

由于你有两个问题,我有两个标题可以单独回答。

PowerShell Runspace State

您可以使用Runspace属性检查PowerShell State对象的状态,该属性指向RunSpaceState .NET enumeration的值:

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

设置IdleTimeout

如果要为PowerShell会话设置IdleTimeout,则需要:

  1. 实例化PSSessionOption
  2. 设置IdleTimeout属性
  3. WSManConnectionInfo对象
  4. 上调用SetSessionOptions()方法

    代码:

    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