Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Catch exception thrown when unable to start a 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 is set to Stop, so this shouldn't be the problem.

When I alter my code to catch [Exception], the exception is caught and "got here" is printed.

Does start-service throw a ServiceCommandException or something else? It looks as though it is but I cannot catch it!

--- Edit ---

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"
}
like image 698
Jack Avatar asked Jul 13 '11 08:07

Jack


2 Answers

Try/Catch works only on terminating errors. Use the ErrorAction parameter with a value of Stop to make the error a terminating error and then you'll be able to catch it:

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

UPDATE:

When you set $ErrorActionPreference to 'stop' (or use -ErrorAction Stop) the error type you get is ActionPreferenceStopException, so you can use it to catch the error.

$ErrorActionPreference='stop'

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

}

like image 65
Shay Levy Avatar answered Nov 15 '22 23:11

Shay Levy


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... ;)

like image 40
Torbjörn Bergstedt Avatar answered Nov 15 '22 22:11

Torbjörn Bergstedt