尝试/捕获似乎没有效果 [英] Try/catch does not seem to have an effect

查看:97
本文介绍了尝试/捕获似乎没有效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PowerShell的新手,我正在尝试通过try / catch语句添加错误处理,但是它们似乎并没有真正捕获错误。这是Powershell v2 CP3。

I am new to powershell, and I am trying to add error handling via try/catch statements, but they don't seem to actually be catching the error. This is powershell v2 CP3.

$objComputer = $objResult.Properties;
$strComputerName = $objComputer.name
write-host "Checking machine: " $strComputerName

try
{
    $colItems = get-wmiobject -class "Win32_PhysicalMemory" -namespace "root\CIMV2" -computername $strComputerName -Credential $credentials
    foreach ($objItem in $colItems) 
    {
        write-host "Bank Label: " $objItem.BankLabel
        write-host "Capacity: " ($objItem.Capacity / 1024 / 1024)
        write-host "Caption: " $objItem.Caption
        write-host "Creation Class Name: " $objItem.CreationClassName      
        write-host
    }
}
Catch 
{
    write-host "Failed to get data from machine (Error:"  $_.Exception.Message ")"
    write-host
}
finally 
{ }  

当它无法与特定计算机联系时,我会在控制台中收到此消息,而不是我的干净捕获消息:

When it fails to contact a specific machine, I get this in console, and not my clean catch message:


Get-WmiObject:RPC服务器是

不可用。 (来自HRESULT的异常:

0x800706BA)在Z:\7.0实习生

Programvare\Powershell\获取AD.ps1中所有计算机的内存

:25 char:34

+ $ colItems = get-wmiobject<<<< -class Win32_PhysicalMemory

-命名空间 root\CIMV2-计算机名$ strComputerName -Credential

$ credentials

+ CategoryInfo:InvalidOperation:(:) [Get-WmiObject],

COMException

+ FullyQualifiedErrorId:GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand


推荐答案

尝试运行远程WMI查询时,我能够复制您的结果。引发的异常不会被尝试/捕获捕获,陷阱也不会捕获该异常,因为它不是终止错误。在PowerShell中,存在终止错误和非终止错误。看来Try / Catch / Finally和Trap仅在出现终止错误时起作用。

I was able to duplicate your result when trying to run a remote WMI query. The exception thrown is not caught by the Try/Catch, nor will a Trap catch it, since it is not a "terminating error". In PowerShell, there are terminating errors and non-terminating errors . It appears that Try/Catch/Finally and Trap only works with terminating errors.

它已记录到$ error自动变量中,您可以测试这些类型的非通过查看$终止错误?自动变量,它将使您知道上一次操作是成功($ true)还是失败($ false)。

It is logged to the $error automatic variable and you can test for these type of non-terminating errors by looking at the $? automatic variable, which will let you know if the last operation succeeded ($true) or failed ($false).

从生成的错误的外观看来,该错误将返回,并且不会包装在可捕获的异常中。以下是生成的错误的痕迹。

From the appearance of the error generated, it appears that the error is returned and not wrapped in a catchable exception. Below is a trace of the error generated.

PS C:\scripts\PowerShell> Trace-Command -Name errorrecord  -Expression {Get-WmiObject win32_bios -ComputerName HostThatIsNotThere}  -PSHost
DEBUG: InternalCommand Information: 0 :  Constructor Enter Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: InternalCommand Information: 0 :  Constructor Leave Ctor
Microsoft.PowerShell.Commands.GetWmiObjectCommand: 25857563
DEBUG: ErrorRecord Information: 0 :  Constructor Enter Ctor
System.Management.Automation.ErrorRecord: 19621801 exception =
System.Runtime.InteropServices.COMException (0x800706BA): The RPC
server is unavailable. (Exception from HRESULT: 0x800706BA)
   at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementScope.InitializeGuts(Object o)
   at System.Management.ManagementScope.Initialize()
   at System.Management.ManagementObjectSearcher.Initialize()
   at System.Management.ManagementObjectSearcher.Get()
   at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
errorId = GetWMICOMException errorCategory = InvalidOperation
targetObject =
DEBUG: ErrorRecord Information: 0 :  Constructor Leave Ctor
System.Management.Automation.ErrorRecord: 19621801

为您的代码解决的方法可能是:

A work around for your code could be:

try
{
    $colItems = get-wmiobject -class "Win32_PhysicalMemory" -namespace "root\CIMV2" -computername $strComputerName -Credential $credentials
    if ($?)
    {
      foreach ($objItem in $colItems) 
      {
          write-host "Bank Label: " $objItem.BankLabel
          write-host "Capacity: " ($objItem.Capacity / 1024 / 1024)
          write-host "Caption: " $objItem.Caption
          write-host "Creation Class Name: " $objItem.CreationClassName      
          write-host
      }
    }
    else
    {
       throw $error[0].Exception
    }

这篇关于尝试/捕获似乎没有效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆