VMware Cloud Community
ultan
Contributor
Contributor

Return code for tag

We have the following script in assigning tags to VMs.

#Get the tag Name

$Tag = get-tag -name $tag_name

#Get the VM

$vms = get-vm -name $VM

#Tag the VM

$vms | New-TagAssignment -Tag $Tag

The $tag_name and the $VM parameters are passed in via ansible

However, I want to add some extra conditional logic to the script

I want to create the tag itself, if it does not exist

Something like:

if ($Tag = get-tag -name $tag_name) == false

then

$tag = New-tag -name $tag_name -Category 'Port-Groups'

If you try and assign a tag that does not exist to a VM, it will spit back an error. Likewise if you try and create a tag that already exists.

Is there an easier way to search for a tag, that will return a boolean if there is a match?

0 Kudos
1 Reply
LucD
Leadership
Leadership

You could go with a try-catch construct

try{

   $Tag = Get-Tag -Name $tag_name -ErrorAction Stop

}

catch {

   $tag = New-tag -name $tag_name -Category 'Port-Groups'

}


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

0 Kudos