【问题标题】:How to test connectivity to a remote computer in powershell如何在PowerShell中测试与远程计算机的连接
【发布时间】:2020-02-01 14:24:28
【问题描述】:

文档中建议了两种方法,这两种方法都完全无法确定远程计算机是否可用于 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”。 在 line:2 char: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"}

知道怎么做吗? (如果我能摆脱错误并强制它返回真或假,我会很高兴Test-WSMan

【问题讨论】:

  • 您需要将-ErrorAction Stop 添加到您的命令中,以便在 Try / Catch 中捕获它。否则它将直接通过它。 Test-WSMan -ComputerName destinationcomputer -ErrorAction Stop
  • @leosenko 您的问题让我觉得您需要一种“测试连接性”的方法。但是,您的开头段落指出“...确定远程计算机是否可用于 powershell 远程处理”。您是在测试连接性还是在测试计算机是否可用于 PowerShell 远程处理(不完全相同,对吗?)?此外,客户端计算机和远程计算机是域或工作组的成员,还是...?

标签: powershell powershell-3.0 powershell-4.0


【解决方案1】:

测试 $?运行 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'

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多