try/catch 好像没有效果 [英] Try/catch does not seem to have an effect

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

问题描述

我是 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 "rootCIMV2" -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 实习生
ProgramvarePowershell获取
的内存AD.ps1:25 char:34
中的所有计算机+ $colItems = get-wmiobject <<<<-class "Win32_PhysicalMemory"
-namespace "rootCIMV2" -computername $strComputerName -Credential
$凭据
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],
COM异常
+ FullQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

推荐答案

我在尝试运行远程 WMI 查询时能够复制您的结果.抛出的异常不会被 Try/Catch 捕获,Trap 也不会捕获它,因为它不是终止错误".在 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:scriptsPowerShell> 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 "rootCIMV2" -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
    }

这篇关于try/catch 好像没有效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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