Powershell Functions for tags

Some quick powershell functions for tags in ESXi enjoy:

#add tag to vm
function add_tag_to_vm($VM, $TAG)
{
 Get-VM –Name $VM | New-TagAssignment –Tag $TAG

}
#Add a tag to all virtual machines in folder
function add_tag_to_all_vm_in_folder($FOLDER,$TAG){

get-folder $FOLDER | get-vm | New-TagAssignment –Tag “$TAG”

}
#List all vm's with specific tag
function get_vms_with_tag($TAG){

$tags = Get-VM –Tag “$TAG”
 return $tags

}
#Check for the presence of a tag on VM
function check_vm_for_tag($VM, $TAG)
{
 $checkfortag = get-vm $VM -tag $TAG
 $havetag = get-vm | where {$checkfortag.name -contains $_.name} 
 return $havetag

}



#Remove tag from VM
function remove_tag_from_vm($VM, $TAG){
 
 $myVM = Get-VM $VM
 $myTagAssignment = Get-TagAssignment -TagAssignment $TAG $myVM
 Remove-TagAssignment $myTagAssignment -Confirm:$False

}

#Remove a tag from all vm's in a folder
function remove_tag_from_all_vm_in_folder($FOLDER, $TAG){

$myVM = get-folder $FOLDER | Get-VM 
 $myTagAssignment = Get-TagAssignment -Category "$TAG" $myVM
 Remove-TagAssignment $myTagAssignment -Confirm:$False

}

Leave a Reply

Your email address will not be published. Required fields are marked *

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