PowerShell - 多台服务器上的 get-hotfix - 错误处理

PowerShell - get-hotfix on multiple servers - error handling

我的脚本在检查多台服务器上的多个修补程序时遇到问题。有时我没有到服务器的 rpc 连接,在这种情况下我想将此信息记录到同一个输出文件中。有人可以帮帮我吗?谢谢

$computers =  Get-Content -path C:[=10=]-Scripts\printer\server.txt
$Patch = Get-Content -path C:[=10=]-Scripts\printer\kb.txt
  
foreach ($computer in $computers) {
    foreach ($patch1 in $patch) {
        Try {
            if (get-hotfix -id $patch1 -ComputerName $computer -ErrorAction stop) {
                Add-content "$patch1 is Present in $computer" -path C:[=10=]-Scripts\printer\Hotfix.txt
             }
             Else {
                 Add-content "$patch1 is not Present in $computer" -path C:[=10=]-Scripts\printer\Hotfix.txt
             }
         }
         catch {
             Add-content "can not check $computer" -path C:[=10=]-Scripts\printer\Hotfix.txt
         }
     }
}

在这种情况下,您需要先检查是否可以访问该计算机。如果是这样,循环遍历补丁以报告是否可以找到它们。如果您无法连接到机器,请在日志中只写一个失败行,然后继续下一台计算机。

$computers = Get-Content -path 'C:[=10=]-Scripts\printer\server.txt'
$Patch     = Get-Content -path 'C:[=10=]-Scripts\printer\kb.txt'
$logFile   = 'C:[=10=]-Scripts\printer\Hotfix.txt'
foreach ($computer in $computers) {
    if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
        foreach ($patch1 in $patch) {
            # use -ErrorAction SilentlyContinue here so $hotfix will either become $null or an object
            $hotfix = Get-HotFix -Id $patch1 -ComputerName $computer -ErrorAction SilentlyContinue
            if ($hotfix) {
                "$patch1 is Present in $computer" | Add-Content -Path $logFile
            }
            else {
                "$patch1 is not Present in $computer" | Add-Content -Path $logFile
            }
        }
    }
    else {
        "Can not check $computer" | Add-Content -Path $logFile
    }
}