【问题标题】:PowerShell 2.0 and how to handle exceptions?PowerShell 2.0 以及如何处理异常?
【发布时间】:2011-06-09 04:16:05
【问题描述】:

为什么我在运行这两个简单示例时会在控制台上打印错误消息? 我希望在控制台上打印“错误测试:)”:

Get-WmiObject : RPC 服务器是 不可用。 (HRESULT 的例外情况: 0x800706BA) 在行:3 字符:15 + Get-WmiObject

试图除以零。在线:3 字符:13 + $i = 1/ + CategoryInfo : 未指定: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RuntimeException

第一个例子:

try
{
    $i = 1/0   
    Write-Host $i     
}
catch [Exception]
{ 
    Write-Host "Error testing :)" 
}

第二个例子:

try
{
    Get-WmiObject -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk 
}
catch [Exception]
{ 
    Write-Host "Error testing :)" 
}

非常感谢!

【问题讨论】:

    标签: powershell exception-handling powershell-2.0


    【解决方案1】:

    第一个例子

    错误发生在编译/解析时(PowerShell 足够聪明),因此代码甚至没有被执行,它确实无法捕获任何东西。试试这个代码,你会发现一个异常:

    try
    {
        $x = 0
        $i = 1/$x
        Write-Host $i
    }
    catch [Exception]
    {
        Write-Host "Error testing :)"
    }
    

    第二个例子

    如果您在全局范围内设置$ErrorActionPreference = 'Stop',那么您将按预期打印“错误测试:)”。但是您的$ErrorActionPreference 大概是'Continue':在这种情况下,没有终止错误/异常,您只会得到引擎向主机打印的非终止错误消息。

    除了全局$ErrorActionPreference 选项,您还可以使用Get-WmiObject 参数ErrorAction。尝试将其设置为Stop,您将捕获异常。

    try
    {
        Get-WmiObject -ErrorAction Stop -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk
    }
    catch [Exception]
    {
        Write-Host "Error testing :)"
    }
    

    【讨论】:

    • 因此,如果 $ErrorActionPreference 设置为 'Continue'(默认设置),您只会打印出错误消息并且脚本正常继续?
    • 如果 $ErrorActionPreference 设置为 'Stop' 那么脚本执行是否会在第一次未处理的异常时停止?
    • 是的,完全正确。就个人而言,我发现这个默认选项令人困惑并且有点危险:它可能会经常导致意外的延续。默认情况下,我更喜欢“停止”,这就是我首先在我的 PS 配置文件中所做的。
    • 您也可以使用通用参数-ErrorAction SilentlyContinue 抑制它并使用通用参数-ErrorVariable someVariableName 捕获错误,以便您可以测试它:Get-WmiObject -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk -ErrorAction SilentlyContinue -ErrorVariable noWMI; if($NoWMI) { Write-Host "Error testing :)" }
    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2016-04-25
    • 2011-05-09
    • 2014-02-28
    • 2017-10-11
    • 1970-01-01
    • 2011-05-29
    相关资源
    最近更新 更多