Powershell:无法启动服务时抛出Catch异常

时间:2011-07-13 08:58:55

标签: exception service powershell try-catch

我似乎无法捕获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"
}

3 个答案:

答案 0 :(得分:12)

Try / Catch仅适用于终止错误。使用值为Stop的ErrorAction参数使错误成为终止错误然后您将能够捕获它:

try
{
    start-service "SomeUnStartableService" -ErrorAction Stop
}
catch
{
    write-host "got here"
}

更新:

当您将$ ErrorActionPreference设置为'stop'(或使用-ErrorAction Stop)时,您获得的错误类型是ActionPreferenceStopException,因此您可以使用它来捕获错误。

$ErrorActionPreference='stop'

try
{
    start-service SomeUnStartableService
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
    write-host "got here"
}

}

答案 1 :(得分:3)

我通常不限制catch-phrase,而是使用catch-block中的逻辑测试来处理异常:

try
{
  start-service "SomeUnStartableService" -ea Stop
}
catch
{
   if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
   {
      #do this
   }
   else
   {
      #do that
   }
}

可能不那么干净,可能导致巨大的捕获障碍。但如果它有效......;)

答案 2 :(得分:1)

要发现您的例外,您可以使用:

try
{
  start-service "SomeUnStartableService" -ea Stop
}
catch
{
 $_.exception.gettype().fullname
}

编辑:以下是SystemException

的旁路
try
{
  start-service "SomeUnStartableService" -ea Stop
}
catch [SystemException]
{
 write-host "got here"
}