am trying to catch a specific exception in a powershell script. Thecodeblock underneath is trying to do this, when the given exception is being thrown the script should ignore it:
try
{
Stop-WebAppPool $webServerSettings.applicationPool
}
catch [System.InvalidOperationException]
{
}
Unfortunately this does not seem to work, I still am getting this response:
Stop-WebAppPool : Object on target path is already stopped.
At F:\Portal.Update.ps1:12 char:2
+ Stop-WebAppPool $webServerSettings.applicationPool
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Stop-WebAppPool], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.IIs.PowerShell.Provider.StopAppPoolCommand
There are a few options I tried:
- Passing the 'ErrorAction Stop' parameter value to the command. Now I do not have the error, but the script stops, that is not what I want.
- Passing the 'ErrorAction SilentlyContinue' parameter value to the command. But this will only work when catching all types of exceptions, which I do not want because if the application pool does not exist, I want the exception to be thrown.
UPDATE: I found a way to work around this problem: Just read out the $_.exception variable and with GetType() get the real exception type, but having a function in a catch does not seem to right way to go:
try
{
Stop-WebAppPool $webServerSettings.applicationPool
}
catch
{
if ($_.Exception.GetType().Name -eq "InvalidOperationException")
{
return
}
throw
}