Chendrayan Venkatesan

2 minute read

Introduction

A friend asked, How to pull resource groups tags, including resource information? Yes, it is the most common ask, and there are many ways to accomplish it! Time is precious, considering that let us skip the legacy methods like using the Az module, REST API, or SDK’s to query the Azure resources in the definitive loops. You are accountable for 200 + subscription and send a report of Azure resources in some schedules. The report should help the target audience to know the owner’s email (tag value) and Azure resource information in the resource groups.

The below query retrieves the information and it is faster!

$Query = @"
Resources
    | project id, subscriptionId, resourceGroup, name, type, location
    | join kind=inner(
    ResourceContainers
        | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
        | project id, subscriptionId, resourceGroup, owner = tags.Owner , location , name , type) 
        on subscriptionId , resourceGroup
        | project-away subscriptionId1, resourceGroup1 , name1 , type1 ,location1
"@

How to use it in PowerShell?

Not a difficult task, import the module Az.ResourceGraph and use the below script.

$Query = @"
Resources
    | project id, subscriptionId, resourceGroup, name, type, location
    | join kind=inner(
    ResourceContainers
        | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
        | project id, subscriptionId, resourceGroup, owner = tags.Owner , location , name , type) 
        on subscriptionId , resourceGroup
        | project-away subscriptionId1, resourceGroup1 , name1 , type1 ,location1
"@
$Results = Search-AzGraph -Query $Query -First 5000

Yes, you are correct! The script above will fetch the first 5000 records! Remaining? I came across a super cool blog of Stephane Lapointe and did a minor modification.

$Query = @"
Resources
    | project id, subscriptionId, resourceGroup, name, type, location
    | join kind=inner(
    ResourceContainers
        | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
        | project id, subscriptionId, resourceGroup, owner = tags.Owner , location , name , type) 
        on subscriptionId , resourceGroup
        | project-away id1, subscriptionId1, resourceGroup1 , name1 , type1 ,location1
"@
$pageSize = 5000
$iteration = 0
$searchParams = @{
    Query = $($Query)
    First = $pageSize
}
[System.Collections.ArrayList]$results = @()
do {
    $iteration += 1
    $pageResults = Search-AzGraph @searchParams -Verbose
    $searchParams.Skip += $pageResults.Count
    $results.AddRange($pageResults)
} while ($pageResults.Count -eq $pageSize)