我是 Powershell 的新手,但对某些价值观的了解足以构成危险。话虽如此,考虑到我以前从未使用过“Function”值,我正在以一点“新鲜感”来处理此代码行。
我想做的是使用下面的代码并创建一个可以触发代码块的 if/else 语句。我遇到的问题是,无论该值是什么,我仍然会错误地读取语句中的“True”或“False”值。代码如下:
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
}
Test-pendingreboot
$PendingReboot = Test-PendingReboot
if ($PendingReboot -eq 'False') {
write-output "Value is False"
}else{
write-output "Value is True"
}
但是,每次我尝试运行此命令时,我总是得到以下输出,这与输出结果相反。
PS C:\Windows\system32> .\testing for Install 2.ps1
True
Value is False
但是,如果我采用第一个“if”语句并说“-eq 'False'”,我似乎会得到与以前相同的结果,这让我挠头并认为我做错了什么。
#Example of the code change
if ($PendingReboot -eq 'True') {
write-output "Value is False"
}else{
write-output "Value is True"
}
#Result
True
Value is False
这取决于 PowerShell 如何评估比较。它将始终尝试使用左侧对象的类型。在这种情况下,您的函数返回布尔值
$true
或 $false
。然后,它尝试将字符串 'true'
转换为该类型,任何非 null 或 0 的值都将计算为 $true
。您可以输入 if ($PendingReboot -eq 'watermelon')
,就 PowerShell 而言,它的含义与 if ($PendingReboot -eq 'True')
相同。请改用 if ($PendingReboot -eq $true)
或 if ($PendingReboot -eq $false)
。或者,由于 if
语句实际上只是在寻找 $true
或 $false
本身,你可以这样做:
if (-Not $PendingReboot) {
write-output "Value is False"
}else{
write-output "Value is True"
}
就我个人而言,我会使用
!
简写为 -Not
并执行 if(!$PendingReboot){
,但这只是我的想法。