Search code examples
azureazure-devopsazure-powershell

How to pass specific values for Get-AzSubscription


We have a command to get all the subscriptions - Get-AzSubscription | Set-Azcontext and set for that to work with multiple subscriptions.

How do we fetch a specific subscription from Get-AzSubscription and pass that for Set-Azcontext?

In order to do that I have tried below:

$subscription = Get-AzSubscription -TenantId "tenant id" | where-object{$_.Name -like 'required name*'} 
$subscription | Set-AzContext

Is there any better way to do the same?


Solution

  • There is nothing wrong with your method as long as:

    • You can easily write the filter clause to include all the required subscriptions. If there is no consistent naming scheme you might end up with lots of ... -or ... -or ... clauses which is messy.
    • You are happy that your script will automatically start to act on any new subscriptions added to your tenancy which match your filter clause.

    If however:

    • You don't have good naming scheme so it's difficult to write a simple filter.
    • The script must act only on the specified subscriptions.

    Then you could do this:

    $subs = @('Sub 1','Live Sub','2 Test','Deb')
    
    $subs | get-azsubscription -SubscriptionName {$_} | set-azcontext