Search code examples
powershellsubscription

How can I get the Subscription Name if i know the resource Group Name using Powershell


So, I have the resource Group name and i want to programmatically (using powershell) set the subscription to the incoming resource group. When i do a Get-AzResourceGroup I get the ResourceId which contains the the subscription id as part of a long string /subscriptions/<subscription id here>/resourceGroups/resourcegroupname. Is there a way to extract the subscription Id from that string?


Solution

  • You can get your subscription ID by triggering the below. You will also need to have azure cli installed.

    az account list  --refresh --query "[?contains(name, 'YOUR_SUBSCRIPTION')].id"
    

    You can also split the output from powershell.

    $myinput= "/subscriptions/xxxxxx-xxxxxx-xxxxxx-xxxxx-xxxxxx/resourceGroups/resourcegroupname".Split("/")
    
    Write-Host $myinput[2]