Search code examples
azureazure-cli

Getting Subscription ID with Resource Group without setting az context


I have a tenant with multiple subscriptions. When I first login using Connect-AzAccount, it shows a message "TenantId 'xxxxx-xxxxx-xxx-xxx' contains more than one active subscription. First one will be selected for further use. To select another subscription, use Set-AzContext."

But I want to be able to do Get-AzResourceGroup -name 'abcd'.

The problem is resource group abcd is not under the first selected subscription selected from the login command.

I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.

tried to clear the context clear-azContext but that signs me out.


Solution

  • I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.

    After reproducing from my end, Using the below script I could able to achieve your requirement.

    $ResourceGroupName = Read-Host "Enter the resource group name you are searching for"
    Get-AzSubscription | ForEach-Object {
        $subscriptionName = $_.Name
        $subscriptionId = $_.SubscriptionId
        Set-AzContext -SubscriptionId $subscriptionId
        (Get-AzResourceGroup).ResourceGroupName | ForEach-Object {     
            If ($ResourceGroupName -eq $_) {
                [PSCustomObject] @{
                    Subscription  = $subscriptionName
                    SubscriptionId = $subscriptionId
                    ResourceGroup = $_
                }
            }
        }
    }
    

    RESULTS:

    enter image description here