Powershell: Catch exception thrown when unable to start a service Powershell: Catch exception thrown when unable to start a service powershell powershell

Powershell: Catch exception thrown when unable to start a service


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

}


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


To discover your exception you can use :

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

Edited : Here is a kind of bypass with SystemException

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