Set the default location in Azure PowerShell

How to set the default location for Azure PowerShell cmdlets so you don’t need to specify it with each command.

In a Twitter discussion yesterday Gregor Suttie (@gregor_suttie) mentioned that being able to set a default region in Azure would be a nice feature. Whilst he was looking for this to be implemented across the multiple different control methods (Portal, CLI, etc) - I did suggest a way that this was currently possible in PowerShell.

The trick behind this is to use the PowerShell preference variable $PSDefaultParameterValues. This allows you to specify a default value for a given cmdlet and parameter.

To demonstrate let’s create two Resource Groups in the UK South region using New-AzResourceGroup but without specifying the -location parameter:

1$PSDefaultParameterValues.Add("New-AzResourceGroup:Location","uksouth")
2New-AzResourceGroup -Name "test-rsg-01"
3New-AzResourceGroup -Name "test-rsg-02"

Both resource groups are created in the “UK South” region, as defined in our default.

This is great, but would involve a $PSDefaultParameterValues.Add line for each of the cmdlets in the Azure PowerShell module which used the Location parameter: New-AzVM, New-AzResourceGroup, etc. etc. . Luckily $PSDefaultParameterValues can use wildcard entries, and thanks to the consistency in PowerShell cmdlet and parameter naming we can set the default location for all cmdlets containing -Az in their name:

1$PSDefaultParameterValues.Add("*-Az*:Location","uksouth")

And then test with a variety of cmdlets:

1New-AzVM -Name MyVm -Credential (Get-Credential) -ResourceGroupName "test-rsg-02"
2New-AzAppServicePlan -ResourceGroupName "test-rsg-02" -Tier Free -Name "test-asp-01"

Note that the presence of this default doesn’t interfere with Azure module cmdlets that don’t require the location parameter, for example this still works:

1Start-AzVM -Name MyVM -ResourceGroupName "test-rsg-02"

Where a non-default Region is required, the location can still be explicitly specified and this will override the default setting, for example:

1New-AzResourceGroup -Name "test-rsg-03" -Location eastus

If you are normally always working in the same region then you could set this value in your Powershell profile so the default would be present in all sessions. Alternatively, it could be incorporated into a short function which you call when you want to set a new default, for example for a different customer or project.

1function Set-AzDefaultLocation {
2      param(
3            [string]$location
4      )
5      $PSDefaultParameterValues.Add("*-Az*:Location",$location)
6}