I need to retrieve the "owner" tag that is associated to all Resource Groups for all Subscriptions in our tenant. I seem to be getting records that don't exist in the tenant. Maybe I'm going about this wrong but I thought I would iterate through all subscriptions and then iterate through all Resource groups and then go through the tag information. I get the same records for most of these resource groups. Can anyone spot the issue?
# 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
}
}
}
}
I would recommend using Search-AzGraph
to query the Resource Manager API, it's much easier and faster with KQL than it will ever be with the individual cmdlets.
The query can be read as:
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
'@