Is it possible to handle Get-AzureManagedCache exception in Powershell?

I am writing a script to set up a Redis cache in Azure. Before setting up a new cache, I want to check for its existence by doing this:

    $cache = Get-AzureManagedCache -Name $cacheName 

      

If the cache doesn't exist, it throws this "exception":

Get-AzureManagedCache: cache service 'PrototypeFOO' not found In C: \ builds \ repos-scm \ branches \ 2.6 \ 2.6.0 \ scm \ AzureDeploymentSandbox \ Scripts \ Create-RedisCache.ps1: 39 char: 15 + $ cache = Get -AzureManagedCache -Name $ cacheName + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: CloseError: (:) [Get-AzureManagedCache], ArgumentException + FullyQualifiedErrorId: Microsoft.Azure.Commands.ManagedCache.GetAzureManagedCache

So I wrap it up in a try / catch block like this:

try
{
    $cache = Get-AzureManagedCache -Name $cacheName 
}
catch 
{
    Write-Host "Catching the exception"
}

      

And when I run it, it jumps right over the catch statement and continues processing. I can add "-EA SilentlyContinue" to the first line to suppress the message, but I am concerned that it will suppress legitimate errors as well, so I would like to avoid that. Any thoughts on how to handle this exception?

+3


source to share


1 answer


Save the try / catch block, but add -ErrorAction Stop

to the Azure call.



Alternatively, you can set $ErrorActionPreference='Stop';

at the top of your script, which will automatically make all errors the same as in .NET.

+2


source







All Articles