Error Trapping

Welcome Forums General PowerShell Q&A Error Trapping

This topic contains 3 replies, has 3 voices, and was last updated by

1 year, 2 months ago.

  • Author
  • #90716

    Points: 0
    Rank: Member

    #I am new to powershell # Trying to get memory usage information of few servers. I was able to get the result for few servers and not for few others(i get "RPC server unavailable" error) I'm guessing that's a firewall issue and i'm ok with that but i need the list of servers that the command failed to run. I tried to run below "script" with no luck.

    $x = get-content .\abc.txt
    foreach($a in $x)
    { $wmi = gwmi -class win32_operatingsystem -computername $a -errorvariable err } 
    if ($err -gt 0)
    { write-host"$y" }

    I got the information that i need by comparing the result that i have got and the original text file. But trying to know the better way to trap the error

  • #90718

    Points: 38
    Rank: Member

    Try using a Try/Catch, like so:

    foreach ($a in (Get-Content .\abc.txt)) {
        try {
            $WMI = Get-WmiObject -Class win32_operatingsystem -ComputerName $a -ErrorAction STOP
        catch {
            Write-Host "$a failed with error: $_"

    You can use $WMI to use that data later on, but if it fails it writes the computer name and the error to the screen. You can take Write-Host and change that to something like this to output to a log file:

    "$a failed with error: $_" | Out-File $path -append
    • #90725

      Points: 0
      Rank: Member

      That worked.Thank you!

  • #90736

    Points: 266
    Helping Hand
    Rank: Contributor

The topic ‘Error Trapping’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort