Joost
Joost

Reputation: 1913

Loop through Azure objects and filter on tags

I have a collection of Azure objects (Virtual Machines, Data Warehouses or Analysis Services) and I want to loop through that collection, but also filter out objects with a certain tag.

enter image description here

For example get all Analysis Services that don't have a tag called "Environment" with the value "Production".

How do I specify the Where-Object filter (tried several ways without success)

cls

# Login to Azure
#Login-AzureRmAccount | Out-Null 

# Selecting the right subscription
#Select-AzureRmSubscription -SubscriptionName "MySubscription" | Out-Null 


# Get all my Analysis Services, but leave out those with the tag Environment=Production
$AnalysisServicesServers = Get-AzureRmAnalysisServicesServer | Where-Object {$_.Tag -notcontains @{Environment="Production";}}

# Loop Through the collection and to something
foreach ($AnalysisServicesServer in $AnalysisServicesServers)
{
    $AnalysisServicesServer                                                      # Show all properties
    Write-Host "1 Name $($AnalysisServicesServer.Name)"                          # Show Name
    Write-Host "2 Tags count [$($AnalysisServicesServer.Tag.Keys.Count)]"        # Show # of tags
    Write-Host "3 Tags Values [$($AnalysisServicesServer.Tag.Values)]"           # Show values
    Write-Host "4 Tags Keys [$($AnalysisServicesServer.Tag.Keys)]"               # Show keys
    Write-Host "5 Tags Keys [$($AnalysisServicesServer.Tag.Keys["Environment"])]" # NOT WORKING
}

enter image description here

Upvotes: 2

Views: 3496

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36277

So the Tag property is a hashtable. There are multiple ways to access the values of a hashtable, but I'll use the one that you have already attempted, but just got the syntax a little bit wrong. Here's how I would accomplish what you're looking for.

$AnalysisServicesServers = Get-AzureRmAnalysisServicesServer | Where-Object {$_.Tag['Environment'] -ne "Production"}

That may throw errors if you have results that don't have an 'Environment' tag on them, but it'll get you the results that you're looking for.

Upvotes: 5

Related Questions