Azure Powershell (QnD)
Common Commands
Connect and Select
Authenticate with Azure, list subscriptions for tenants and select a subscription to work with.
Connect-AzAccount -Tenant <tenant id> Get-AzSubscription Select-AzSubscription -SubscriptionId <id>
Command Context
Get Azure tenants that there is an authenticated session for.
Get-AzTenant | select id,name
See and set current context for Azure Powershell commands
This shows subscription and tenant info for current connections.
Get-AzContext -ListAvailable | fl
Set-AzContext -Tenant "xyz"
Set-AzContext -Subscription "xyz"
Remove item from available context
(Get-AzContext -ListAvailable).Name
Remove-Context -Name <context name>
Get Resources
List all resources in the current subscription.
Get-AzResource
Get-AzResource | select Name,Type,ResourceGroupName,SubscriptionId | Export-Csv resources.csv
Loop Over All Subscriptions
Loop over all subscriptions in a tenant and run some command against them.
foreach ($sub in Get-AzSubscription -TenantId "xyz") { Write-Host $sub.id }
Example
Example of getting creation/last update timestamp for all custom policy definitions.
foreach ($sub in Get-AzSubscription -TenantId "xyz") { Get-AzPolicyDefinition -SubscriptionId $sub.id | select -ExpandProperty Properties | where {$_.PolicyType -eq "Custom"} | select DisplayName -ExpandProperty Metadata | select DisplayName, createdOn, updatedOn | fl }
Loop over all subscriptions in a tenant and for each subscription run some commands.
foreach ($sub in Get-AzSubscription -TenantId "xyz") { Set-AzContext -Subscription $sub.id | Out-Null # # Other commands # }
Set-AzContext -Tenant "xyz" foreach ($sub in Get-AzSubscription) { Set-AzContext -Subscription $sub.id | Out-Null # # Other commands # }
Loop Over Resource Groups
Get-AzResourceGroup | foreach { $_.ResourceGroupName # # Do something with RG info # }
List Policy Assignments
Set-AzContext -Tenant "xxxx…" foreach ($sub in Get-AzSubscription) { Set-AzContext -Subscription $sub.Id $p += Get-AzPolicyAssignment } $p | select -ExpandProperty Properties | select DisplayName,Scope
List All Extension on VMs
function AvGet-VMExtensions ($TenantId) { $extList = @() foreach ($sub in Get-AzSubscription -TenantId $TenantId) { Get-AzVM | foreach { $vm = $_.Name $ext = Get-AzVMExtension -VMName $_.Name -ResourceGroupName $_.ResourceGroupName $ext | foreach { $obj = [PSCustomObject]@{ Name = $vm ExtName = $_.Name } $extList += $obj } $extList | Format-Table -AutoSize } $extList | Tee-Object $env:tmp\vm-exts.txt } }
List Subnets with no associated NSG
foreach ($sub in Get-AzSubscription -TenantId "xxxx") { Set-AzContext -Subscription $sub.id | Out-Null (Get-AzVirtualNetwork | foreach {$_.Subnets} | where {$_.NetworkSecurityGroup -eq $null}).Name }
Enumerating Resources
§
$azResources = Get-AzResource $azResources | foreach { $_.ResourceId }
§
Get-AzResourceGroup | foreach {Get-AzStorageAccount -ResourceGroupName $_.ResourceGroupName}