powershelltry-catchhotfix

PowerShell - get-hotfix on multiple servers - error handling


I have a problem with my script to check multiple hotfixes on multiple servers. Sometimes I don't have a rpc connection to a server, in this case I want to log this information to the same output file. Can someone please help me? thanks

$computers =  Get-Content -path C:\00-Scripts\printer\server.txt
$Patch = Get-Content -path C:\00-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:\00-Scripts\printer\Hotfix.txt
             }
             Else {
                 Add-content "$patch1 is not Present in $computer" -path C:\00-Scripts\printer\Hotfix.txt
             }
         }
         catch {
             Add-content "can not check $computer" -path C:\00-Scripts\printer\Hotfix.txt
         }
     }
}

Solution

  • In this case, you need to first check if the computer can be reached. If so, loop over the patches to report if they can be found or not. In you cannot reach the machine, write just one failure line in the log and proceed with the next computer.

    $computers = Get-Content -path 'C:\00-Scripts\printer\server.txt'
    $Patch     = Get-Content -path 'C:\00-Scripts\printer\kb.txt'
    $logFile   = 'C:\00-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
        }
    }