PowerShell for Azure: automate resources with the Az module
João Barros
04 de October de 2024
1 min read
The Az PowerShell module is the most complete command-line interface for Azure, with over 10,000 cmdlets covering all services. Ideal for automation, bulk provisioning and recurring administration tasks.
Installation and authentication
Install-Module -Name Az -Scope CurrentUser -Force
# Interactive login (opens a browser for MFA)
Connect-AzAccount -TenantId "your-tenant-id"
# Login with a Service Principal (for automation/CI-CD)
$secPwd = ConvertTo-SecureString $env:SP_SECRET -AsPlainText -Force
$cred = New-Object PSCredential($env:SP_CLIENT_ID, $secPwd)
Connect-AzAccount -ServicePrincipal -Credential $cred -TenantId $env:TENANT_ID
# Select subscription
Set-AzContext -SubscriptionId "subscription-id"
Create and manage resources
# Create a resource group
New-AzResourceGroup -Name "rg-analytics-prod" -Location "westeurope"
# Create a storage account
New-AzStorageAccount `
-ResourceGroupName "rg-analytics-prod" `
-Name "stadatalakeprod" `
-Location "westeurope" `
-SkuName "Standard_LRS" `
-Kind "StorageV2" `
-EnableHierarchicalNamespace $true # ADLS Gen2
# List VMs in a resource group
Get-AzVM -ResourceGroupName "rg-analytics-prod" | Select-Object Name, Location, PowerState
Maintenance script — nightly shutdown of dev VMs
# Run via an Azure Automation Runbook or scheduled task
$rg = "rg-dev"
$tags = @{ Environment = "Dev"; AutoStop = "true" }
Get-AzVM -ResourceGroupName $rg | Where-Object { $_.Tags["AutoStop"] -eq "true" } |
ForEach-Object {
Write-Output "Stopping VM: $($_.Name)"
Stop-AzVM -ResourceGroupName $rg -Name $_.Name -Force -AsJob
}
Get-Job | Wait-Job | Receive-Job
Export an inventory to Excel
# List all Azure resources and export
$resources = Get-AzResource | Select-Object Name, ResourceType, ResourceGroupName, Location
$resources | Export-Csv -Path "azure_inventory.csv" -NoTypeInformation -Encoding UTF8
Conclusion
The Az module is indispensable for Azure administrators and engineers. Automate repetitive tasks (stopping VMs, inventories, resource creation), integrate into Azure Automation Runbooks for scheduled execution and treat PowerShell as lightweight IaC for day-to-day operations.