【发布时间】:2011-10-04 07:47:51
【问题描述】:
我似乎无法捕获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] 时,异常被捕获并打印“到这里”。
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"
}
【问题讨论】:
标签: exception service powershell try-catch