2
votes

I'm writing a PowerShell script to list Resource Groups across Azure Subscriptions.

Get-AzureRmSubscription | 
select -ExpandProperty name |
 % { 
     Get-AzureRmResourceGroup | select -ExpandProperty resourcegroupname
 }

This code works. It returns results like this.

Resource group 1     
Resource group 2
Resource group 3 

How can I tweak the code to get the output like below?

Subscription 1,Resource group 1     
Subscription 1,Resource group 2
Subscription 2,Resource group 3 

Thank you so much.

2

2 Answers

2
votes

Untested:

Get-AzureRmSubscription | 
 % { 
   $subscrName = $_.Name
   Select-AzureSubscription -Current -SubscriptionName $name
   (Get-AzureRmResourceGroup).resourcegroupname | % {     
     [pscustomobject] @{
       Subscription = $subscrName
       ResourceGroup = $_
     }
   }
 }

Note: The above changes the session's current subscription. In your real code you may want to restore the previously current one afterwards.

The above outputs custom objects with .Subscription and .ResourceGroup properties; if you really only want to output strings, use:
"$name,$_"

5
votes

Adding to @mklement's great answer, here is how you would do it with the latest Azure PowerShell Az module instead of AzureRM:

Get-AzSubscription | ForEach-Object {
    $subscriptionName = $_.Name
    Set-AzContext -SubscriptionId $_.SubscriptionId
    (Get-AzResourceGroup).ResourceGroupName | ForEach-Object {     
        [PSCustomObject] @{
            Subscription = $subscriptionName
            ResourceGroup = $_
        }
    }
}

To change to the active subscription, we can change the context with Set-AzContext, and pass the SubscriptionId From Get-AzSubscription. Should also be able to get away with passing the subscription name with Set-AzContext -Subscription $subscriptionName.

If you want to run AzureRM commands with the Az module, you can run Enable-AzureRmAlias, which allows you to use the AzureRM prefixes with Az modules.