Get all subscriptions recursive from management groups with PowerShell

$topLvlMgmtGrp = "CHANGETHIS"          # Name of the top level management group
$subscriptions = @()                   # Output array

# Collect data from managementgroups
$mgmtGroups = Get-AzManagementGroup -GroupId $topLvlMgmtGrp -Expand -Recurse

$children = $true
while ($children) {
    $children = $false
    $firstrun = $true
    foreach ($entry in $mgmtGroups) {
        if ($firstrun) {Clear-Variable mgmtGroups ; $firstrun = $false}
        if ($entry.Children.length -gt 0) {
            # Add management group to data that is being looped throught
            $children       = $true
            $mgmtGroups    += $entry.Children
        }
        else {
            # Add subscription to output object
            $subscriptions += New-Object -TypeName psobject -Property ([ordered]@{'DisplayName'=$entry.DisplayName;'SubscriptionID'=$entry.Name})
        }
    }
}

$subscriptions

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.