Powershell:无法启动服务时引发捕获异常 [英] Powershell: Catch exception thrown when unable to start a service
问题描述
我似乎无法捕捉到Start-Service
引发的异常.这是我的代码:
I seem unable to catch an exception thrown by Start-Service
. Here is my code:
try
{
start-service "SomeUnStartableService"
}
catch [Microsoft.PowerShell.Commands.ServiceCommandException]
{
write-host "got here"
}
运行此命令时,会引发但未捕获到异常:
When I run this, the exception is thrown but not caught:
*Service 'SomeUnStartableService' start failed.
At line:3 char:18
+ start-service <<<< "SomeUnStartableService"
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand*
$ErrorActionPreference
设置为停止",所以这不应该是问题.
$ErrorActionPreference
is set to Stop, so this shouldn't be the problem.
当我将代码更改为catch [Exception]
时,将捕获异常并打印此处获得".
When I alter my code to catch [Exception]
, the exception is caught and "got here" is printed.
start-service
是否抛出ServiceCommandException
或其他东西?看起来好像是,但是我抓不到它!
Does start-service
throw a ServiceCommandException
or something else? It looks as though it is but I cannot catch it!
-编辑---
理想情况下,我可以编写以下内容,如果start-service
没有引发异常,并且仅捕获由start-service
引发的异常,则引发异常:
Ideally I could write the following, and throw an exception if start-service
did not throw an exception, and only catch an exception thrown by start-service
:
try
{
start-service "SomeUnStartableService"
throw (new-object Exception("service started when expected not to start"))
}
catch [Microsoft.PowerShell.Commands.ServiceCommandException]
{
write-host "got here"
}
推荐答案
我通常不限制catch短语,而是使用catch块中的逻辑测试来处理异常:
I usually don't limit the catch-phrase but handle the exceptions with logical tests within the catch-block:
try
{
start-service "SomeUnStartableService" -ea Stop
}
catch
{
if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
{
#do this
}
else
{
#do that
}
}
可能不那么干净,并且可能导致巨大的捕获块.但是,如果可行...;)
Maybe not as clean, and may result in huge catch blocks. But if it works... ;)
这篇关于Powershell:无法启动服务时引发捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!