Create an Azure Resource Group with Powershell

Resource groups are a fundamental component of Azure. Your VMs, Networks, Storage account(s), etc. all live in resource groups. Before we run the command we need to figure out WHERE we want to put the resource group. You can do this a few ways; one way is to pick from Microsoft’s website here. Another way is to list them from powershell:

List locations:

#List all Locations
Get-AzLocation

#To filter the list
Get-AzLocation | where {$_.Displayname -like "*west*"}

The info we need to is the Location. Once we have our location, we are ready to create our new resource group. You can do so with the following command. Make sure you are connected to Azure, you can see how to connect here.

Create Resource Group (Single Command):

New-AzResourceGroup -Name "Testing42" -Location "westus"

Create Resource Group (With Error Checking):

This is the same thing as above, just with a try-catch statement for error checking. This is what you would want to use in a larger script to make sure the resource group already existed.

$LocationName = "westus"
$ResourceGroupName = "Testing42"

#Check for resource group and create if it does not exist
try {
    Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction Stop
    Write-Host "Resource group exists.  VM will be placed along side existing resources" -ForegroundColor DarkGreen
}
catch {
    Write-Host "Resource group does not exist.  It will now be created." -ForegroundColor DarkRed
    try {
        New-AzResourceGroup -Name $ResourceGroupName -Location $LocationName -Verbose -ErrorAction Stop        
        Write-Host "Completed!" -ForegroundColor DarkGreen        
    }
    catch {
        Write-Host "Failed to create resource group"
        exit        
    }
}
Creating a resource group

After running the command we get output that it was successful. It takes a minute or two for the resource group to show up in the Azure portal. If we want remove the resource group that can be done with this command.

Remove Resource Group:

Get-AzResourceGroup -Name "Testing42" | Remove-AzResourceGroup
Removing a resource group
Tagged : /

Leave a Reply

Your email address will not be published. Required fields are marked *