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

PowerShell调整IF判断顺序后Test-Connection输出结果翻转问题

问题原因

你遇到的问题是PowerShell的类型自动转换机制导致的判断逻辑错误:

  • Test-Connection -Quiet返回的结果是布尔类型的$true/$false,不是字符串类型的'True'/'False'
  • 当你用布尔值和字符串做相等比较时,PowerShell会自动把右侧的字符串转换为布尔类型再比较:
    • 任何非空字符串转布尔值都会得到$true,哪怕字符串内容是'False'
    • 只有空字符串转布尔值才会得到$false

你两次写法的实际运行逻辑:

  1. 第一次写法If ($TestConnection -eq 'True'):
    字符串'True'转布尔为$true,实际判断逻辑等价于If ($TestConnection -eq $true),所以结果正确
  2. 第二次写法If ($TestConnection -eq 'False'):
    字符串'False'是非空字符串,转布尔为$true,实际判断逻辑等价于If ($TestConnection -eq $true),所以原本开机的设备会命中这个条件,输出is off,结果完全翻转

修复方案

不要用字符串做布尔判断,直接用PowerShell原生的布尔值即可,推荐两种写法:

写法1:显式和布尔常量比较

ForEach ($computer in $ADComputers)
{
    $TestConnection = Test-Connection -ComputerName $computer -Quiet
    If ($TestConnection -eq $false)
    {
        Write-Host "$computer is off"
    }
    Else 
    {
        Write-Host "$computer is on"
    }
}

写法2:更简洁的布尔判断(推荐)

PowerShell支持直接对布尔变量取反,不需要写相等比较,代码可读性更高:

ForEach ($computer in $ADComputers)
{
    $TestConnection = Test-Connection -ComputerName $computer -Quiet
    If (-not $TestConnection)
    {
        Write-Host "$computer is off"
    }
    Else 
    {
        Write-Host "$computer is on"
        # 后续执行注册表修改操作的逻辑写在这里即可
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:27:03