PowerShell 2.0 以及如何处理异常?

标签 powershell exception-handling powershell-2.0

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

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:3 char:15 + Get-WmiObject <<<< -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand



或者

Attempted to divide by zero. At line:3 char:13 + $i = 1/ <<<< 0
+ CategoryInfo : NotSpecified: (:) [], 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 足够聪明),因此代码甚至没有执行,也确实无法捕获任何内容。试试这个代码,你会发现一个异常:

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 :)"
}

关于PowerShell 2.0 以及如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4691874/

相关文章:

c# - 如何在不丢失堆栈跟踪的情况下重新抛出 TargetInvocationException 的内部异常

PowerShell - "Delete all files from this folder except one"的最紧凑方式

powershell - 如何从给定的 URL 解析基本路径?

json - 为 TFS 团队设置区域时参数 'patch' 出现 ArgumentNullException

powershell - 同一文件(Powershell)的结果不同

node.js - 使用 PowerShell Invoke-Command 和 Process 使 stdout 显示在控制台上

C#: 'throw'是否退出当前函数?

python - 在 Python 中记录未捕获的异常

powershell - 什么是用于 checkin / checkout 文件的好的 Powershell 动词?

powershell - 如何使用 powershell 的 read-host 功能接受外部服务的密码?