PowerShell 2.0如何处理异常?
为什么我在运行这两个简单示例时在控制台上打印错误消息? 我希望我在控制台上打印“错误测试:)”,而不是:
Get-WmiObject :RPC 服务器是 不可用。 (HRESULT 的异常: 0x800706BA) 在行:3 字符:15 + Get-WmiObject <<<<< -计算机名可能是.nonexisting.domain.com -Credential(获取凭据)-Win32_logicdisk 类 + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COM异常 +FullyQualifiedErrorId:GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
或
尝试除以零。行数:3 字符:13 + $i = 1/ <<<<< 0
+ 类别信息:未指定:(:) [], 父包含错误记录异常 + FullQualifiedErrorId:运行时异常
第一个示例:
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 :)"
}
非常感谢!
Why I get error message printed on the console when running these two simple samples ?
I want that I get "Error testing :)" printed on the console insted of:
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
or
Attempted to divide by zero. At line:3
char:13
+ $i = 1/ <<<< 0
+ CategoryInfo : NotSpecified: (:) [],
ParentContainsErrorRecordException
+ FullyQualifiedErrorId : RuntimeException
First example:
try
{
$i = 1/0
Write-Host $i
}
catch [Exception]
{
Write-Host "Error testing :)"
}
Second example:
try
{
Get-WmiObject -ComputerName possibly.nonexisting.domain.com -Credential (Get-Credential) -Class Win32_logicaldisk
}
catch [Exception]
{
Write-Host "Error testing :)"
}
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个示例
错误发生在编译/解析时(PowerShell 足够聪明),因此代码甚至没有执行,并且确实无法捕获任何内容。尝试使用此代码,您将捕获异常:
第二个示例
如果您全局设置
$ErrorActionPreference = 'Stop'
,那么您将得到“错误测试:)”打印,如下所示预期的。但是您的$ErrorActionPreference
可能是'Continue'
:在这种情况下,没有终止错误/异常,您只会得到引擎打印到主机的非终止错误消息。除了全局
$ErrorActionPreference
选项,您还可以使用Get-WmiObject
参数ErrorAction
。尝试将其设置为Stop
,您将捕获异常。First example
The error happens at compile/parsing time (PowerShell is clever enough), so that the code is not even executed and it cannot catch anything, indeed. Try this code instead and you will catch an exception:
Second example
If you set
$ErrorActionPreference = 'Stop'
globally then you will get "Error testing :)" printed, as expected. But your$ErrorActionPreference
is presumably'Continue'
: in that case there is no terminating error/exception and you just get the non terminating error message printed to the host by the engine.Instead of the global
$ErrorActionPreference
option you can also play withGet-WmiObject
parameterErrorAction
. Try to set it toStop
and you will catch an exception.