文档中建议了两种方法,这两种方法对于确定远程计算机是否可用于 powershell 远程处理完全没有用。
Test-Connection
没有用,因为它只发送 ping,但是,目标可能正在运行 Intel AMT,因此响应 ping,或者可能没有运行 winRM 服务,因此这不提供有用的信息。Test-WSMan
应该测试 Windows RM 服务的可用性,但只有当 WinRM 工作时它才有效,否则(计算机关闭或 WinRM 未运行)它会给出一个错误:Test-WSMan:客户端无法连接到请求中指定的目标。验证目标上的服务正在运行并且正在接受请求。请查阅在目标(最常见的是 IIS 或 WinRM)上运行的 WS-Management 服务的日志和文档。如果目标是 WinRM 服务,请在目标上运行以下命令来分析和配置 WinRM 服务:“winrm Quickconfig”。 行:2 字符:1
- Test-WSMan -ComputerName 目标计算机
-
+ CategoryInfo : InvalidOperation: (destinationcomputer:String) [Test-WSMan], InvalidOperationException + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.TestWSManCommand
因此,我尝试将 Test-WSMan
封装在 try-catch
命令中,但它仍然给出错误,但并未真正捕获:
Try {
Test-WSMan -ComputerName destinationcomputer
} catch {
write-output "not working"}
知道如何做到这一点吗? (如果我能消除错误并强制它返回 true 或 false,我会对 Test-WSMan
感到满意)
最佳答案
测试$?运行 test-wsman 后。
Test-WSMan destinationcomputer
if (! $?) {
'not working'
}
您也可以这样做,因为失败不会返回标准输出:
if (!(Test-WSMan destinationcomputer)){
'not working'
}
另请参阅Check if a command has run successfully
也在 powershell 7 中:
Test-WSMan destinationcomputer || 'not working'
关于powershell - 如何在 powershell 中测试与远程计算机的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017773/