Filter for VMs that don’t have two specific tags attached to it

This post was originally published on this site

Hey everyone, I hope you guys are doing good.

 

I would like to get a result for a query where a VM does not have two specific tags attached to it.

 

The environment I am working with contains several hundred VMs, possibly changing on a daily basis.

I need a report which VM is not considered for a backup because either the tag is missing or a different tag is applied.

 

Filtering for VMs without tags is easy:

# VMs with no tags attached to them
$VMsWithNoTags = Get-VM | ?{(Get-TagAssignment $_) -eq $null} | sort

 

Also filtering for VMs with one specific tag — absolutely doable:

# VMs with the Tag "BCK_enabled" attached
$VMsWithTags = Get-VM -Tag "BCK_enabled" | Sort-Object

 

But when it comes to two filters, I’m smitten.

In my experience looping through arrays and matching tags is very time consuming and I’m way off when it comes to writing performant (or even good) code.

 

I tried it several ways but I always fail because a single VM object lists as many lines as the amount of tags applied to it, something like:

PS C:UsersAdministrator> Get-VM SYV0001 | Get-TagAssignment
Tag                                      Entity                        
---                                      ------                        
Service/SP2013PRD                        SYV0001                       
Operating System/Win2008R2               SYV0001                       
System Type/Development                  SYV0001                       
Backup/BCK_WIN                           SYV0001                       
Backup/BCK_Enabled                       SYV0001                        

 

When I do a “match” operation it will never be accurate as it loops through the result list line by line. So … how would I match a “BCK_enabled” AND “BCK_disabled” tag against the whole list of tags attached to a single VM so that I can find the ones that have neither of these tags applied? I would want to loop through the whole inventory eventually but failed to do so as of yet.

 

Hope you guys can help.

 

Thanks in advance!

BR

NC

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.