Skip to content

Add NSX-T Tags with PowerCLI

I don’t think the NSX-T PowerCLI module operates intuitively compared to most PowerShell modules I have worked with. It took me a while to figure out how to add NSX-T tags to a virtual machine with PowerCLI. I had to piece together Information from the documentation and various forums. I’ve put some notes here to help others (and remind myself in the future😊). Assuming you have done a Connect-VIServer  and a Connect-NsxtServer something like this should let you add tags to a VM easily.

# You need to get the NSX-T service we want to interact with - vm inventory for tagging
$vmservice = Get-NsxtService -Name com.vmware.nsx.fabric.virtual_machines

$vm = Get-VM "NameOfVMToTag"

# Create a list of tags we want to attach to the previously mentioned virtual machine
$tags = $vmservice.Help.addtags.virtual_machine_tag_update.Create()

# Target the virtual machine by its UUID
$tags.external_id = $vm.ExtensionData.Config.InstanceUuid

# Create a specific tag
$tag = $vmservice.Help.addtags.virtual_machine_tag_update.tags.Element.Create()
$tag.Scope = "MyScope"
$tag.Tag = "MyTag"

# Add the tag to the list of tags
$tags.tags.Add($tag) | Out-Null

# Perform the operation with the list of tags on the specified VM
$vmservice.addtags($tags)

And that’s all there is to it to add NSX-T Tags with PowerCLI. Once you have an understanding of this basic functionality, it becomes much easier to do a mass add of multiple tags to multiple machines with a foreach.

Also, note that $vmservice.addtags will only add the tags you specify. It should not impact any tags that are already assigned to the virtual machine. If you want to remove tags you can use $vmservice.removetags. $vmservice.updatetags will replace all existing tags with the ones you specify. $vmservice.Help should help you figure out the syntax for those.

2 thoughts on “Add NSX-T Tags with PowerCLI”

  1. Hi Adam, thanks for the wonderful post! I ran into an issue You cannot call a method on a null-valued expression on the line “$tags.tags.Add($tag) | Out-Null”. But when I debug it, $tag has value. Can you help please?

Leave a Reply

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