Error Trapping

This topic contains 3 replies, has 3 voices, and was last updated by  Sam Boutros 2 weeks, 4 days ago.

  • Author
    Posts
  • #90716

    Venky
    Participant

    #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

    Jeremy Corbello
    Participant

    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

      Venky
      Participant

      That worked.Thank you!

  • #90736

    Sam Boutros
    Participant

You must be logged in to reply to this topic.