用于从所有资源组获取标签信息的Powershell脚本

问题描述 投票:0回答:1

我需要检索与租户中所有订阅的所有资源组关联的“所有者”标签。我似乎得到了租户中不存在的记录。也许我的做法是错误的,但我想我应该遍历所有订阅,然后遍历所有资源组,然后遍历标签信息。对于大多数这些资源组,我获得了相同的记录。有人能发现问题吗?

# Connect-AzAccount
$subs = Get-AzSubscription
$count = 1
foreach ($sub in $subs) {
    Set-AzContext -SubscriptionId $sub.SubscriptionId
    Write-Host $count. $sub.Name
    $count ++
    $resource_groups = Get-AzResourceGroup
    foreach ($rg in $resource_groups) {
        Write-Host '       ' $rg.ResourceGroupName
        $rgTags = Get-AzTag -Name 'owner'
        if ($rgTags -ne $null) {
            foreach ($tag in $rgTags.Values) {
                Write-Host '               '$tag.Name
            }
        }
    }
}
azure powershell tags azure-resource-manager
1个回答
2
投票

我建议使用

Search-AzGraph
来查询 资源管理器 API,使用 KQL 比使用单个 cmdlet 更容易、更快。

查询可以理解为:

对于

resourcecontainers
中的每个容器,其类型为
microsoft.resources/subscriptions/resourcegroups
并且其
owner
标签不为 null 或空项目属性
subscriptionId
resourceGroup
ownertag

Search-AzGraph -Query @'
    resourcecontainers
    | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
    | extend ownertag = tags.owner
    | where isnotempty(ownertag)
    | project subscriptionId, resourceGroup, ownertag
'@
© www.soinside.com 2019 - 2024. All rights reserved.