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

Jac*_*ack 10 powershell service exception try-catch

我似乎无法捕捉到被抛出的异常Start-Service.这是我的代码:

try
{
    start-service "SomeUnStartableService"
}
catch [Microsoft.PowerShell.Commands.ServiceCommandException]
{
    write-host "got here"
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,抛出异常但没有捕获:

*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*
Run Code Online (Sandbox Code Playgroud)

$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"
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*evy 13

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

try
{
    start-service "SomeUnStartableService" -ErrorAction Stop
}
catch
{
    write-host "got here"
}
Run Code Online (Sandbox Code Playgroud)

更新:

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

$ErrorActionPreference='stop'

try
{
    start-service SomeUnStartableService
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
    write-host "got here"
}
Run Code Online (Sandbox Code Playgroud)

}


Tor*_*edt 3

我通常不限制捕获短语,而是通过捕获块内的逻辑测试来处理异常:

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

也许不那么干净,并可能导致巨大的捕获块。但如果它有效的话...;)