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

PowerShell函数返回值在if/else判断中结果异常求助

解决PowerShell布尔值判断异常问题

问题根源

你的Test-PendingReboot函数返回的是布尔类型的$true或$false,但判断逻辑中错误地将其与字符串类型的'False'/'True'进行比较。PowerShell对不同类型的比较会执行隐式类型转换,导致判断结果与预期不符。

另外你代码中额外调用了一次Test-pendingreboot,其输出会干扰对变量赋值结果的判断,也是需要修正的点。

解决方案

方案1:直接用布尔值作为判断条件(推荐)

PowerShell的if语句可直接识别布尔值,无需额外比较操作:

function Test-PendingReboot
{
 if (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -EA Ignore) { return $true }
 if (Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -EA Ignore) { return $true }
 if (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -EA Ignore) { return $true }
 try {
   $util = [wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities"
   $status = $util.DetermineIfRebootPending()
   if(($status -ne $null) -and $status.RebootPending){
     return $true
     }
 }catch{}

 Return $False
 }

# 移除多余的函数调用,确保变量值为唯一一次检测结果
$PendingReboot = Test-PendingReboot

if (-not $PendingReboot) { 
   Write-Output "Value is False"
}else{ 
   Write-Output "Value is True"
}

方案2:与布尔值而非字符串比较

如果坚持使用-eq比较,要匹配布尔类型的$false/$true:

$PendingReboot = Test-PendingReboot

if ($PendingReboot -eq $false) { 
   Write-Output "Value is False"
}else{ 
   Write-Output "Value is True"
}

关键说明

  • 移除多余的Test-pendingreboot调用,避免其输出干扰对变量结果的判断,同时保证$PendingReboot的值是单次检测的准确结果。
  • PowerShell中布尔值$true/$false与字符串'True'/'False'属于不同类型,直接比较会触发隐式转换,导致非预期结果,必须保证比较两端的类型一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:25:22