简体   繁体   English

是否可以在Powershell中处理Get-AzureManagedCache异常?

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

I am writing a script to setup a Redis cache in Azure. 我正在编写一个脚本来在Azure中设置Redis缓存。 Prior to setting up a new cache, I want to check for its existence by running this: 在设置新缓存之前,我想通过运行以下命令来检查它是否存在:

    $cache = Get-AzureManagedCache -Name $cacheName 

If the cache doesn't exist, it outputs this "exception": 如果缓存不存在,则输出此“异常”:

Get-AzureManagedCache : Cache Service 'PrototypeFOO' was not found At 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 Get-AzureManagedCache:找不到缓存服务'PrototypeFOO'在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 in a try/catch block like this: 所以我将它包装在try / catch块中,如下所示:

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

And when I run it, it skips right over the catch statement and keeps on processing. 当我运行它时,它会跳过catch语句并继续处理。 I am able to append "-EA SilentlyContinue" to the first line to suppress the message, but I am concerned that will suppress legit errors as well, so I would like to avoid that. 我可以将“-EA SilentlyContinue”附加到第一行来抑制消息,但我担心这也会抑制合法错误,所以我想避免这种情况。 Any thoughts on how to handle this exception? 有关如何处理此异常的任何想法?

Keep the try/catch block, but add -ErrorAction Stop to the Azure call. 保留try / catch块,但将-ErrorAction Stop添加到Azure调用。

Alternatively, you can set $ErrorActionPreference='Stop'; 或者,您可以设置$ErrorActionPreference='Stop'; at the top of your script, which will automatically make all Errors act like they do in .NET. 在脚本的顶部,这将自动使所有错误像在.NET中一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM