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

标签 powershell powershell-3.0 powershell-4.0

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

  1. Test-Connection 没有用,因为它只发送 ping,但是,目标可能正在运行 Intel AMT,因此响应 ping,或者可能没有运行 winRM 服务,因此这不提供有用的信息。

  2. 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/

相关文章:

azure - 仅当在具有 azure 访问权限的 Windows 帐户上运行时,使用 ClientID 访问 Blob 存储才有效

c# - 将关联数组从 C# 传递到 Powershell

powershell - 使用 Powershell 更改 SERVER 的 Home FTP SSL 证书

powershell - 如何使用 Powershell 2.0 版解压缩 Zip 文件?

Powershell 在模块内加载模块 [范围]

arrays - 奇怪的行为:输入参数(具有以 “D”或 “L”字符结尾的多个值)

powershell-3.0 - PowerShell 模块 - 在导入模块时传递参数

powershell - 合并文本文件并添加文件名和行号 - Powershell

powershell - 选择对象不返回对象?

powershell - 为什么 “where”不能按我期望的在这里选择某些结果?