如何在 Powershell 中测试与远程计算机的连接

How to test connectivity to a remote computer in powershell

文档中建议了两种方法,这两种方法对于确定远程计算机是否可用于 powershell 远程处理完全没有用。

  1. Test-Connection 没有用,因为它只发送 ping,但是,目的地可能是 运行ning Intel AMT,因此响应 ping 也可能不是 运行ning winRM 服务,所以这没有提供任何有用的信息。

  2. Test-WSMan 应该测试 Windows RM 服务的可用性,但它只在 WinRM 工作的情况下工作,否则(计算机关闭或 WinRM 不是 运行ning) 它给出一个错误:

    Test-WSMan:客户端无法连接到请求中指定的目标。确认目标上的服务是 运行ning 并且正在接受请求。请参阅目标上的 WS-Management 服务 运行ning 的日志和文档,最常见的是 IIS 或 WinRM。如果目标是 WinRM 服务,运行 在目标上执行以下命令来分析和配置 WinRM 服务:"winrm quickconfig"。 在 line:2 char:1

    • Test-WSMan -ComputerName 目标计算机
    • + CategoryInfo          : InvalidOperation: (destinationcomputer:String) [Test-WSMan], InvalidOperationException
      + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.TestWSManCommand
      

所以我尝试在try-catch命令中包含Test-WSMan,但它仍然给出错误,并没有真正被捕获:

    Try {
         Test-WSMan -ComputerName destinationcomputer
    } catch {
         write-output "not working"}

知道怎么做吗? (如果我可以消除错误并将其强制为 return true 或 false,我会对 Test-WSMan 感到满意)

测试$?在 运行 test-wsman.

之后
Test-WSMan destinationcomputer
if (! $?) { 
  'not working'
}

你也可以这样做,因为失败 returns 没有标准输出:

if (!(Test-WSMan destinationcomputer)){
  'not working'
}

另见 Check if a command has run successfully

同样在 powershell 7 中:

Test-WSMan destinationcomputer || 'not working'