skip to Main Content

I have multiple azure tenants, each having multiple subscriptions, and I have to run a single PowerShell script for all my subscriptions.

This can be achieved using Azure CLI, and it works perfectly.

I use Azure CLI as below;

$az_account = (az account list --query "[].[name]" -o tsv)
foreach ($account in $az_account) {
    az account set --name $account
    #<RUN SCRIPTS HERE>#
}

But in some situations, I have to use the Az PowerShell command instead of Azure CLI.

So could anyone help me

  1. How to run Az PowerShell commands for multiple subscriptions
  2. Or the Az PowerShell profile file path ( same as Azure CLI which is C:Users%USER.AzureazureProfile.json ).

2

Answers


  1. Chosen as BEST ANSWER

    Resolution

    After a couple of tries, finally found some methods to solve my issue. posting the same here might be helpful for someone.

    You can connect all the subscriptions using the below commands

    Connect-AzAccount -Tenant "xxxx-xxxxx-xxxx-xxx" -Subscription "xxxx-xxxxx-xxxx-xxx"
    

    To List all the connected subscriptions

    Get-AzContext -ListAvailable | Select-Object Name, Subscription, Tenant
    

    enter image description here

    If you want to rename to a friendly Name,

    Rename-AzContext -SourceName "Azure subscription 1 (xxxxx-xxxx-xxxx-xxxx-xxxx) - xxxxx-xxxx-xxx-xxxx-xxxx-xxx - [email protected]" -TargetName "MySubscription"
    

    To save these profiles to file,

    Save-AzContext -Path "C:UsersjawadDownloadsAzpwshProfile.json"
    

    You can import any time these profiles using the below command, (test first clear the profile Clear-AzContext -Force)

    Import-AzContext -Path "C:UsersjawadDownloadsAzpwshProfile.json"
    

    Now you easily use for loop to set the subscriptions, for example

    $acc = (Get-AzContext -ListAvailable | Select-Object Name)
    foreach ($account in $acc) {
    >> Select-AzContext $account.Name
    >> Get-AzVM | Export-Csv -Path "inventory.csv"
    >> }
    

    Thank you


    1. How to run Az PowerShell commands for multiple subscriptions

    You can use the below PowerShell Scripts to run the multiple subscription PowerShell commands.

    # Get the Subscription Details using Get-AzSubscription Command
    Get-AzSubscription | ForEach-Object {
        # Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command
        $_ | Set-AzContext
        $subscriptionName = $_.Name
          #<RUN YOUR SCRIPTS HERE>#
    
    }
    

    enter image description here

    1. Or the Az PowerShell profile file path ( same as Azure CLI which is C:Users%USER.AzureazureProfile.json ).

    Refer here for profile file path location

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search