You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows PowerShell 5.1与PS Core 7.1中Test-Connection输出差异问题

差异是否为预期行为

是预期行为。
PowerShell 7.x(Core)为了适配跨平台运行的需求,对Test-Connection cmdlet进行了完全重写:

  • Windows PowerShell 5.1版本的Test-Connection依赖Windows专属的WMI类Win32_PingStatus实现,返回的是WMI管理对象,没有直接提供Latency、Status属性,延迟对应属性名为ResponseTime,状态对应属性名为StatusCode(0代表成功)
  • PowerShell 7.x版本不再依赖WMI,改用.NET跨平台网络API实现,返回自定义的PingStatus类型对象,直接提供Latency、Status属性

两者的实现逻辑和返回对象结构是官方设计的差异,所以运行结果不一致属于预期行为。

如何在两个版本得到一致输出

可以通过计算属性对两种对象的属性做兼容映射,无需主动判断PowerShell版本,运行以下命令即可在两个版本得到结构、取值完全一致的输出:

# Windows PowerShell 5.1 运行
powershell -NoLogo -NoProfile -Command "Test-Connection 10.37.45.128 | Select-Object -Property Address, BufferSize, @{Name='Latency';Expression={if ($_.PSObject.Properties['ResponseTime']) { $_.ResponseTime } else { $_.Latency }}}, @{Name='Status';Expression={if ($_.PSObject.Properties['StatusCode']) { if ($_.StatusCode -eq 0) { 'Success' } else { 'Failed' } } else { $_.Status.ToString() }}}; $PSVersionTable.PSVersion.ToString()"

# PowerShell 7.x 运行
pwsh -NoLogo -NoProfile -Command "Test-Connection 10.37.45.128 | Select-Object -Property Address, BufferSize, @{Name='Latency';Expression={if ($_.PSObject.Properties['ResponseTime']) { $_.ResponseTime } else { $_.Latency }}}, @{Name='Status';Expression={if ($_.PSObject.Properties['StatusCode']) { if ($_.StatusCode -eq 0) { 'Success' } else { 'Failed' } } else { $_.Status.ToString() }}}; $PSVersionTable.PSVersion.ToString()"

内容的提问来源于stack exchange,提问作者lit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:45:04