Powershell WMIObject错误处理

时间:2015-08-16 17:02:34

标签: powershell

我有一些连接到远程服务器的代码。 如果无法建立与服务器的连接,我需要写入文本文件。我已使用此代码完成此操作:

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
    }

$errorMessage变量未保留错误消息。

任何帮助将不胜感激。 感谢。

1 个答案:

答案 0 :(得分:0)

只需在您的WMI命令中包含错误操作首选项,例如:

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

这应该捕获非终止错误。 我还会包含一个通用的Catch块来捕获未明确提及的任何异常。

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

Technet topic on try catch