Search Azure resources by tag

There are many ways to organize resources in Azure and one best practice is to set tags and be able to query resources based on tags. Most commonly, tags are used for cost management where filters and dashboards can be made to slice/dice resources to find cost across tags and their values.

Here we see a simple method to search Azure resource within a subscription based on a tag and its value.

First we select the subscription into the Powershell context.

Select-AzSubscription -SubscriptionId <xxxx>

 

Then we search all resources:

Get-AzResource

 

Then we improve the previous query to conduct inline search based on presence of a tag and presence of a value.

Get-AzResource | Where-Object {$_.Tags -ne $null} | Where-Object {$_.Tags['Dept'] -eq "Billing"}

Then you can further restrict your search to Virtual Machines containing a tag named Dept having value of Billing

Get-AzResource |Where-Object{$_.ResourceType -eq 'Microsoft.Compute/virtualMachines'} | Where-Object {$_.Tags -ne $null} | Where-Object {$_.Tags['Dept'] -eq "Billing"}

Finally, you can run this in a loop across all subscriptions that the current user has permissions onto, complete code below

Connect-AzAccount
$subs = Get-AzSubscription  
foreach ($sub in $subs) {
    Select-AzSubscription -SubscriptionId $sub.Id
    $VMs = Get-AzResource | Where-Object { $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' } | Where-Object { $_.Tags -ne $null } | Where-Object { $_.Tags['Dept'] -eq "Billing" }
    foreach ($vm in $VMs) {

        echo $vm.Name
    }

}

 

 

Leave a Reply