我需要检索与租户中所有订阅的所有资源组关联的“所有者”标签。我似乎得到了租户中不存在的记录。也许我的做法是错误的,但我想我应该遍历所有订阅,然后遍历所有资源组,然后遍历标签信息。对于大多数这些资源组,我获得了相同的记录。谁能发现问题吗?
# 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
}
}
}
}
最佳答案
我建议使用Search-AzGraph
查询Resource Manager API ,使用 KQL 比使用单个 cmdlet 更容易、更快捷。
查询可以理解为:
For each container in
resourcecontainers
where their type ismicrosoft.resources/subscriptions/resourcegroups
and theirowner
Tag is not null or empty project the propertiessubscriptionId
,resourceGroup
,ownertag
.
Search-AzGraph -Query @'
resourcecontainers
| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
| extend ownertag = tags.owner
| where isnotempty(ownertag)
| project subscriptionId, resourceGroup, ownertag
'@
关于azure - 用于从所有资源组获取标签信息的Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77053487/