【问题标题】:How to check if azure resource exists in PowerShell?如何检查 PowerShell 中是否存在 azure 资源?
【发布时间】: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


【解决方案1】:

您可以尝试以下方法:

$KeyVaultName = "keyvaultname"
$ResourceGroupName = "resourcegroupname"
$KeyVaultLocation = "keyvaultlocation"
$KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue

if($null -eq $KeyVault){
    $KeyVault = Get-AzKeyVault -VaultName $KeyVaultName -Location $KeyVaultLocation -InRemovedState -ErrorAction SilentlyContinue
    if ($null -eq $KeyVault) {
      New-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -Location $KeyVaultLocation
    } else {
      Write-Host "$KeyVaultName exists but is in soft-deleted state"
    }
}
else{
    Write-Host "$KeyVaultName already exists"
}

本质上,我们在这里所做的是首先检查 Key Vault 是否存在并处于活动状态。如果我们没有找到任何 Key Vault,那么我们正在检查 Key Vault 是否处于软删除状态。如果没有找到结果,那么我们将继续创建新的 Key Vault。

但是,请注意,Key Vault 名称是全球唯一的,因此您的 New-AzKeyVault Cmdlet 很可能会失败。

【讨论】:

  • 非常感谢您的回答。这完美!最后一个问题,如果密钥库名称在全球范围内存在,我们该怎么办。我们应该添加什么条件?
  • 如何检查一个azure资源NAME是否全局存在,以防止powershell终端出现错误。
猜你喜欢
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多