PowerShell调整IF判断顺序后Test-Connection输出结果翻转问题
问题原因
你遇到的问题是PowerShell的类型自动转换机制导致的判断逻辑错误:
Test-Connection -Quiet返回的结果是布尔类型的$true/$false,不是字符串类型的'True'/'False'- 当你用布尔值和字符串做相等比较时,PowerShell会自动把右侧的字符串转换为布尔类型再比较:
- 任何非空字符串转布尔值都会得到
$true,哪怕字符串内容是'False' - 只有空字符串转布尔值才会得到
$false
- 任何非空字符串转布尔值都会得到
你两次写法的实际运行逻辑:
- 第一次写法
If ($TestConnection -eq 'True'):
字符串'True'转布尔为$true,实际判断逻辑等价于If ($TestConnection -eq $true),所以结果正确 - 第二次写法
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
相关产品推荐
相关产品推荐

