检查 Azure 资源组是否存在 - Azure Powershell

33
我想验证资源组是否存在,所以我认为以下代码应该返回 true 或 false,但它没有输出任何内容。

我正在尝试验证 ResourceGroup 是否存在,因此我认为以下代码应该返回 true 或 false,但它没有输出任何内容。

$RSGtest = Find-AzureRmResource | Format-List ResourceGroupName | get-unique
$RSGtest -Match "$myResourceGroupName"

为什么我没有得到任何输出?

5个回答

54

更新:

现在应该使用新的跨平台AZ PowerShell 模块中的Get-AzResourceGroup cmdlet。

Get-AzResourceGroup -Name $myResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue

if ($notPresent)
{
    # ResourceGroup doesn't exist
}
else
{
    # ResourceGroup exist
}

Translated Answer:

有一个 Get-AzureRmResourceGroup 命令:

Get-AzureRmResourceGroup -Name $myResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue

if ($notPresent)
{
    # ResourceGroup doesn't exist
}
else
{
    # ResourceGroup exist
}

1
谢谢,但是有些问题,这是我得到的全部内容: 警告:此 cmdlet 的输出对象类型将在未来版本中进行修改。 - Peter Pavelka
3
如果你遇到了 -ev-ea 的问题,它们是 -ErrorVariable-ErrorAction 的简写形式。我知道这容易引起困惑,所以在这里提供一个参考链接 - trailmax
2
@trailmax 你说得对,我不应该在我的代码片段中使用别名。我会改正的。 - Martin Brandl
1
感谢您更新以添加新的 cmdlet 更新! - Sam
除非Get-AzResourceGroup错误是由于其他完全不相关的错误(例如网络问题)而导致RG不存在。出于这个原因,我更喜欢另一个答案,在其中枚举所有RG并搜索所需的RG(当然,它的性能较低,但在大多数情况下,您不会在单个子中拥有那么多RG)。 - Ohad Schneider
显示剩余3条评论

5

试试这个

$ResourceGroupName = Read-Host "Resource group name"
Find-AzureRmResourceGroup | where {$_.name -EQ $ResourceGroupName}

在新的 Az Powershell 版本中:$existingResourceGroup = Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -eq $resourceGroup } | Select-Object -First 1; if (!$existingResourceGroup) { ... } - Ohad Schneider

3

我是PS的新手,正在寻找解决这个问题的方法。

与其直接在SO上搜索,我试图独自调查使用PS帮助(以获取更多关于PS的经验),然后我想出了一个可行的解决方案。 然后我搜索了SO,看看我如何与专家的答案相比较。 我猜我的解决方案不太优雅,但更加简洁。我在此报告它,以便其他人可以发表他们的意见:

if (!(Get-AzResourceGroup $rgname -ErrorAction SilentlyContinue))
   { "not found"}
else
   {"found"}

我的逻辑解释:我分析了Get-AzResourceGroup的输出,发现它要么是包含已找到资源组元素的数组,要么是如果未找到组则为空。我选择使用否定(!)形式,虽然比较长但可以跳过else条件。最常见的情况是,如果资源组不存在则创建资源组,如果已存在则不做任何操作。


1

我也在寻找同样的东西,但我的情况有一个额外的条件。

所以我像这样解决了它。要获取场景详细信息请点击此处

$rg="myrg"
$Subscriptions = Get-AzSubscription
$Rglist=@()
foreach ($Subscription in $Subscriptions){
$Rglist +=(Get-AzResourceGroup).ResourceGroupName
}
$rgfinal=$rg
$i=1
while($rgfinal -in $Rglist){
$rgfinal=$rg +"0" + $i++
}
Write-Output $rgfinal
Set-AzContext -Subscription "Subscription Name"
$createrg= New-AzResourceGroup -Name $rgfinal -Location "location"

0

曾经遇到过类似的挑战,我使用下面的脚本解决了它:

$blobs = Get-AzureStorageBlob -Container "dummycontainer" -Context $blobContext -ErrorAction SilentlyContinue

## Loop through all the blobs
foreach ($blob in $blobs) {
    write-host -Foregroundcolor Yellow $blob.Name
    if ($blob.Name -ne "dummyblobname" ) {
        Write-Host "Blob Not Found"
    }
    else {
        Write-Host "bLOB already exist"
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接