我似乎无法捕获抛出的异常Start-Service
。这是我的代码:
try
{
start-service "SomeUnStartableService"
}
catch [Microsoft.PowerShell.Commands.ServiceCommandException]
{
write-host "got here"
}
当我运行它时,抛出异常但未捕获:
*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
设置为“停止”,因此这应该不是问题。
当我将代码更改为catch [Exception]
,异常被捕获并打印“got here”。
Does start-service
扔一个ServiceCommandException
或者是其他东西?看起来好像是,但我抓不到!
- - 编辑 - -
理想情况下,我可以编写以下内容,并在以下情况下抛出异常:start-service
没有抛出异常,只捕获了抛出的异常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"
}
Try/Catch 仅适用于终止错误。使用带有 Stop 值的 ErrorAction 参数使错误成为终止错误,然后您将能够捕获它:
try
{
start-service "SomeUnStartableService" -ErrorAction Stop
}
catch
{
write-host "got here"
}
UPDATE:
当您将 $ErrorActionPreference 设置为“stop”(或使用 -ErrorAction Stop)时,您得到的错误类型是 ActionPreferenceStopException,因此您可以使用它来捕获错误。
$ErrorActionPreference='stop'
try
{
start-service SomeUnStartableService
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
write-host "got here"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)