如何根据 returns 非布尔结果的 cmdlet 做出基于布尔的控制决策?

How do I make boolean based control decisions from a cmdlet that returns non-boolean results?

代码说明了我正在尝试做的事情。如何根据 get-hotfix 等命令行开关的结果使 if 语句以布尔方式工作?本质上,我希望 True 是任何结果,而 false 是 null return.

我相信 PowerShell 已经这样做了,因为任何结果始终被视为布尔值 true,并且没有结果被 returned 为 null。我需要知道 if ($hot -EQ True) 处不会出错的语法。

#get a list of computernames
$inputFile = Read-Host -Prompt "Please enter the directory path of the input file."
#parse the list of computernames into an array.
$info = Get-Content $inputFile

#loop to run the hotfix check against all the computers.
foreach ($Data in $info) {
  $hot =  Get-HotFix -ComputerName $Data | Where-Object hotfixid -EQ KB4338824
    #if patch is found output true to user
    if ($hot -EQ True){
      Write-Host $Data + "is True"    
    }
    #if patch is not found output false to user
    else {
      Write-Host $Data + "is False" 
    }  
  }

选择变量名对理解代码有很大帮助。

  • 检查 属性 值的一种方法是 [string]::IsNullOrEmpty()
  • 我会直接检查 ID Get-Hotfix 不需要 Where-Object
  • 并使用 [PSCustomObject]@{} 到 return 一个 table 轻松保存为 csv 文件。
  • -EA 0-ErrorAction SilentlyContinue
  • 的缩写

## Q:\Test18\SO_52649161.ps1

$ComputerList = Read-Host -Prompt "Please enter the directory path of the input file."
$Computers    = Get-Content $ComputerList
$Hotfix       = 'KB4338824'

$result = ForEach($Computer in $Computers){
    $Installed = (!([string]::IsNullOrEmpty(
        (Get-HotFix -ID $Hotfix -Computer $Computer -EA 0).InstalledOn)))
    [PSCustomObject]@{
        Computer  = $Computer
        Hotfix    = $Hotfix
        Installed = $Installed
    }
}
$result
$result | Export-Csv -Path HotFixSummary.csv -NoTypeInformation

示例输出

Computer Hotfix    Installed
-------- ------    ---------
PC1      KB4338824     False
PC2      KB4338824      True