Powershell WMIObject Error Handling

0

I have some code which connects to remote servers. I need to write into a text-file if a connection to the server cannot be made. I've done so with this code:

try
    {
        $w3wpresult = (get-wmiobject Win32_Process -filter "name like 'w3wp%'" -computername $server | select name, @{l= "Private Memory (GB)"; e={$_.privatepagecount / 1gb}})
        $vmresult = (get-wmiobject Win32_Process -filter "name like 'w3wp%'" -computername $server | select name, @{l= "Virtual Memory (GB)"; e={$_.virtualsize / 1gb}})
        $vmMemory += $server + " @ " + $time + ": " + (($vmresult|%{"$_"})-join',') + "`r`n"
        $w3wpMemory += $server + " @ " + $time + ":" + (($w3wpresult|%{"$_"})-join',') + "`r`n"
    }
    catch [System.Runtime.InteropServices.COMException]
    {
        if($_.Exception.ErrorCode -eq 0x800706BA)
        {
            $errorMessage = "Unable to connect to server" 
        }

        $vmMemory += $server + " @ " + $time + ": " + $errorMessage
        $w3wpMemory += $server + " @ " + $time + ": " + $errorMessage
    }

The $errorMessage variable is not holding the error message.

Any help would be appreciated. Thanks.

powershell
asked on Stack Overflow Aug 16, 2015 by Stephen Sugumar • edited Aug 16, 2015 by Stephen Sugumar

1 Answer

0

just include the Error action preference with your WMI commands like:

(get-wmiobject Win32_Process -filter "name like 'w3wp%'" -computername $server -ErrorAction Stop

This should catch non-terminating errors . I would also include a generic Catch block to catch any exceptions that are not specifically mentioned.

Try
{
  #WMI Commands
}
catch [System.Runtime.InteropServices.COMException]
{
  #Specific error caught
}
Catch
{
  #Generic error caught
}

Technet topic on try catch

answered on Stack Overflow Aug 17, 2015 by Kiran

User contributions licensed under CC BY-SA 3.0