Powershell: Catch exception thrown when unable to start a service

Viewed 28301

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"
}
4 Answers

"Microsoft.PowerShell.Commands.ServiceCommandException" will also be true when not run elevated. Just saying.

Related