VMware Cloud Community
ToddBertschi
Contributor
Contributor

List of VM's and Exclude a tag

PowerCLI version: 12.3.0.17860403

PowerShell version: 5.0.10240.18215

Hello kids. I have an issue that I'm banging my head against. I have a script that pulls VM information down from multiple environments and it works great. The issue I'm running into is that I want to ignore certain VM's. I can't go by name or folder so the best way is of course using tags. I have gone through and tagged all the VM's that I want to ignore with an 'Application/Ignore' tag. My problem is the list I generate has to grab all VM's regardless of their tags but then drop the ones marked 'Ignore' and I'm having issues. I think I'm over thinking or something.

The original code was just a simple

        $view = Get-VM -Name * | Sort-Object

I thought that it would be a simple thing to grab the tag assignment and then if I see the tag, drop it but I'm getting conflicting results. One thing is that not all the VM's have tags so it's possible some are blank or null. That might be my problem. I'm also trying to avoid double looping. This seems like it should be a one-liner add to the above code. This is what I've been toying with.

     $view = Get-VM -Name * | Where-Object {(Get-TagAssignment $_) -notlike 'Application/Ignore'}

Depending on my string search I get nothing or all the VM's with tags and never all the VM except the ones with tags. Anyone have some easy solutions? This is driving me nuts as it should be simple.

Peace

Labels (3)
0 Kudos
3 Replies
ToddBertschi
Contributor
Contributor

So I have it working I think but I don't like it. It feels ... clunky. I ended up creating an array and then looping through to create another array.

    $View = @()  # Clear array

    $vms = Get-VM

    foreach ($vm in $vms) {

      If ((Get-TagAssignment $VM).Tag.Name -notcontains 'Ignore'){

      $view += Get-VM $VM

    }

    }

Anyone have suggestions on a better way to code it or to speed it up?

0 Kudos
LucD
Leadership
Leadership

Not a one-liner (which I strongly dislike), but at least with only one call to the expensive Get-TagAssignment.

$tagName = 'Ignore'
$exclude = (Get-Tag -Name $tagName).Name
$vm = Get-VM
$excludeVM = (Get-TagAssignment -Entity $vm -Tag $tagName).Entity.Name
$vm | where{$excludeVM -notcontains $_.Name} |
Select Name

And you can use multiple tags in $tagName


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
ToddBertschi
Contributor
Contributor

Thank you LucD. That does seem less expensive. I just ran a test and it's longer than I though so I'll replace my code with this and see if it speeds it up.

Peace

0 Kudos