RaviLobo
RaviLobo

Reputation: 508

How to list Resource Groups across Azure Subscriptions using PowerShell?

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.

Upvotes: 2

Views: 18833

Answers (2)

mklement0
mklement0

Reputation: 437052

Note:

  • This answer uses cmdlets from the obsolete AzureRM module, which has since been replaced with the cross-platform Az module - see this announcement.

  • RoadRunner's answer has an updated solution that uses the Az module.


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,$_"

Upvotes: 5

RoadRunner
RoadRunner

Reputation: 26315

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.

Upvotes: 10

Related Questions