If/else 语句查看 windows 更新是否在特定 window 期间安装

If/else statement to see if windows updates were installed during a specific window

有人可以帮助我吗?我想在计算机上 运行 一个 powershell 脚本,如果在特定时间范围内安装了更新,它会告诉我是或否,我写这个的方式,它一直返回未安装。有什么想法吗?

$hotfix1 = Get-HotFix | 

Where 
    ($_.InstalledOn -gt "10/13/2020" -AND $_.InstalledOn -lt "10/16/2020") 


If ($hotfix1 -eq "True") {
write-host "Hotfix is installed"
}
else {
write-host "Hotfix is NOT installed"
}

您可以使用以下代码:

$hotfix1 = Get-HotFix | Where { $_.InstalledOn -gt "10/13/2020" -AND $_.InstalledOn -lt "10/16/2020" }
if ($hotfix1) {
    Write-Host "Hotfix is installed"
} else { 
    Write-Host "Hotfix is NOT installed"
}

由于您是基于管道中的当前对象 ($_) 进行过滤,因此您必须使用脚本块 ({})。

WhereWhere-Object 的别名。当您将脚本块作为位置参数传递时,脚本块将绑定到命令的 -FilterScript 参数。

如果变量是 null、空 string/set、布尔值 false 或 0,则当变量转换为 Boolean 时 PowerShell returns False类型。如果变量包含非零数字、布尔值 true 或 non-empty 对象,PowerShell 在转换为 Boolean 时 returns True。因此,您只需要在条件语句 if 中计算变量,因为 PowerShell 会在计算表达式时将其转换为 Boolean


要按照您预期的方式评估 if 语句,您需要在进行比较之前将 $hotfix1 转换为 Boolean。由于 PowerShell 喜欢通过强制 right-hand 端(RHS)将类型与 LHS 匹配来提供帮助,因此您可以将 RHS 保留为 'true';然而,尽管这在句法上是正确的,但在逻辑上却是不正确的。 'true''false' 是字符串而不是布尔值,因为使用了引号。所以当字符串转换为布尔值时,字符串的字符排列并不重要,因为 PowerShell 只关心它们是否为空。

# A longer hand way of using correct syntax and logic
if ([boolean]$hotfix1 -eq $true) { Write-Host "Hotfix installed" }

# The below syntax is not recommended because both statements evaluate  equally!
# Works only because 'true' is coerced into [boolean]'true', which evaluates to true.
# [boolean]'false' also evaluates to true because the string false is not an empty string
if ([boolean]$hotfix1 -eq 'True') { Write-Host "Hotfix installed" }
if ([boolean]$hotfix1 -eq 'False') { Write-Host "Hotfix installed" }