【发布时间】:2022-01-23 15:49:01
【问题描述】:
我正在尝试使用 PowerShell 检查资源组中是否已存在 azure 密钥保管库。 如果即使在已删除状态下也已存在同名保管库,我只想收到一条用户友好的消息,说明 Key Vault 已存在或捕获异常(如果有)。我不希望终端因错误而爆炸。如果密钥保管库不存在,我想创建一个新的密钥保管库。
我有以下代码:
$KeyVaultName = "Key Vault Name"
$ResourceGroupName = "Resource group name"
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue
if($null -eq $KeyVault){
New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location "Switzerland North"
}
else{
Write-Host "$KeyVaultName already exists"
}
执行代码后,我在终端上收到此错误消息:
New-AzKeyVault :同名的保管库已存在且处于已删除状态。您需要恢复或清除现有的密钥保管库。
我也尝试使用以下代码:
if (!(Test-AzureName -Service $KeyVaultName))
{
New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location "Switzerland North"
}
执行后出现以下错误:
Test-AzureName :未指定默认订阅。使用 Select-AzureSubscription -Default 设置默认订阅。
虽然我只使用了一个订阅。
如果我在这里做错了什么,有人可以告诉我吗?您能否为我提供一种有效的方法来实现这一目标?
【问题讨论】:
-
一般来说,您可以删除
-ErrorActionPreference SilentlyContinue并将Get-AzKeyVault包装在try ... catch块中,而不是处理异常。但是,根据Get-AzKeyVault的文档,您还可以指定一个-InRemoveState开关,这可能会有所帮助 - 请参阅docs.microsoft.com/en-us/powershell/module/az.keyvault/… -
@mclayton 非常感谢您的回答。 InRemoveState 完成了这项工作。
标签: azure powershell azure-keyvault