检测WinRM连接丢失

时间:2019-06-06 19:36:40

标签: c# .net winrm

我使用C#通过WinRM连接到远程PC。

我希望能够尽快检测到连接丢失(但未正确地被远程关闭,例如PC的电源已关闭或以太网电缆已断开)。 我想在不到5秒的时间内检测到连接丢失。有可能吗?

有关信息,我使用此连接运行一些可以持续几分钟的PowerShell命令。理想情况下,无论我是否在这些命令之一的中间,我都希望检测连接丢失。

我的C#代码是:

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(true, ipAddress, 5986, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", accountCredential);
connectionInfo.SkipCACheck = true; // SkipCACheck allows to connect without installing the certificate on the host.
connectionInfo.SkipCNCheck = true; // SkipCNCheck allows server name to not match certificate.
connectionInfo.OpenTimeout = 3000; // 3s
connectionInfo.OperationTimeout = 300000; // 5min
connectionInfo.IdleTimeout = 7200000; // 2h
runspace = RunspaceFactory.CreateRunspace(connectionInfo);

1 个答案:

答案 0 :(得分:0)

我发现ping适用于以下情况:

private bool HostPingable(string host)
    {
        try
        {
            var ping = new Ping();
            var reply = ping.Send(host);
            return reply != null && reply.Status == IPStatus.Success;
        }
        catch (Exception e)
        {
            e.LogException(Logger, host);
        }
        finally { GC.Collect(); }
        return false;
    }

在建立任何WinRM连接之前,您可以运行此命令以查看主机是否在线。

相关问题