Home > Blogs > VMware PowerCLI Blog

Using vSphere Tags with PowerCLI

imageWith the new 5.5 R2 release of PowerCLI we introduced end-to-end support for the vSphere Tagging functionality. You can now automate Tag and TagCategory management, assign tags on objects and search for objects by tag. This blog post will give you an overview of the new functionalities and a couple of useful scripts:

  • One for exporting/importing of tags
  • One for converting the legacy custom attributes to tags

Managing Tag Categories

Tag Categories allow you to group related tags together. When you define a category, you can also specify which object types its tags can be applied to and whether more than one tag in the category can be applied to an object. Creating a category with PowerCLI is easy:

New-TagCategory –Name [name] -Description [description] -Cardinality [single/multiple] –EntityType [list of types]

For example let’s create a category that will contain a tag for each vSphere user. We’ll name this category “Owner” and use it to tag the owners of Virtual Machines. The tags will only be applicable to Virtual Machines and a Virtual Machine can have only one owner. The following script creates such a category:

New-TagCategory –Name “Owner” –Cardinality single –EntityType VirtualMachine

The “-Cardinality” parameter specifies whether a single or multiple tags from this category can be applied to the same object at the same time. If you don’t specify it the default is “single”. The “-EntityType” parameter allows you to specify the object types to which you can attach tags from this category. If you omit the parameter by default the category will be applicable to all supported entity types.

The full list of supported entity types is: VirtualMachine, VM, VMHost, Folder, Datastore, DatastoreCluster, Cluster, ResourcePool, DistributedSwitch, DistributedPortGroup, VirtualPortGroup, VApp, Datacenter, All.

Modifying an existing TagCategory is done through Set-TagCategory cmdlet. You can change its name, description, cardinality (you can only extend it to “multiple”, restricting it to “single” is not possible) and add more entity types (again you can only extend the applicable entity types).

In our previous example the “Owner” category is only applicable to Virtual Machines, however VApps can also have an owner. Let’s modify the category to allow tagging VApps as well:

Get-TagCategory “Owner” | Set-TagCategory –AddEntityType VApp

Removing an existing category is just as easy by using the Remove-TagCategory cmdlet. Note that by removing a category you are also removing all tags in it and any assignments of these tags! Here is an example:

Remove-TagCategory “Owner”

Managing Tags

Once you have a tag category you are able to create new tags in it. This is done through the New-Tag cmdlet. For example in our “Owner” category let’s create a tag for John Smith:

New-Tag –Name “jsmith” –Category “Owner”

You can also create multiple tags – by reading the input values from CSV file or from other cmdlets. Here is how to create tags for each user in the “Example.org” domain:

# Retrieve all user accounts in the “Example.org” domain

$userList = Get-VIAccount –User –Domain “Example.org”

# For each user account create a new tag based on the user’s Id

foreach ($user in $userList) { New-Tag –Category “Owner” –Name $user.Id –Description $user.Description }

Modifying an existing tag is done through the Set-Tag cmdlet. It allows you to change the tag’s name and description:

Get-Tag “jsmith” –Category “Owner” | Set-Tag –Description “John Smith”

Removing a tag is done through Remove-Tag cmdlet, similar to removing a category. When removing a tag you will automatically remove any assignments of this tag.

Now that you have created some tags – it’s time to put them to use. You can assign tag to an entity using the New-TagAssignment cmdlet. Here is how to assign the “jsmith” tag to the VMs that belong to John (we assume they have “jsmith” in their name):

Get-VM –Name *jsmith* | New-TagAssignment –Tag “jsmith”

You can easily retrieve all tag assignments on a given entity:

Get-VM jsmith_vm1 | Get-TagAssignment

Or you can retrieve all VMs that have a given tag associated with them:

Get-VM –Tag “jsmith”

If you want to build a report that displays information about your inventory objects and all tags associated with them – you can do that by using the New-VIProperty cmdlet to add a “Tag” property to your objects. Here is an example of how to do that for the VirtualMachines, but it is easily applicable to other types as well:

# First we want to define the new “Tag” property of the VirtualMachine object

New-VIProperty -Name Tag -ObjectType VirtualMachine -Value `

{ Get-TagAssignment -Entity $args[0] | select -ExpandProperty Tag }

# Now retrieve all VMs and their tags:

Get-VM | select Name, Tag

Exporting and importing tags

Now that you know the basics, let’s do something more advanced. If you have created all your tags with a script using the above commands it’s very easy to run this scrip on another vCenter Server in order to replicate all tags on that server as well. But if you created them by hand how can you replicate them on a different VC? Well, here is one solution, using the attached script ExportImportTags.ps1 you will be able to export your tag configuration from one VC and then import it to another (one or multiple).

To use the script – simply download it from here and save it in a folder of your preference. Start PowerCLI and load the script:

. <path_to_folder>\ExportImportTags.ps1

Then connect to the VC you want to export tags from:

$sourceVC = Connect-VIServer <connection_parameters>

To export all tags use the Export-Tags function. It accepts two parameters, the server from which to export the tags and a destination file where to save them:

Export-Tags –Server $sourceVC –Destination C:\vc1_tags.txt

Then connect to the VC(s) that you want to import those tags to:

$destinationVC = Connect-VIServer <connection_parameters>

To import the tags use the Import-Tags function. It accepts two parameters, the server on which to import the tags and a source file from which to read them (the file produced by Export-Tags earlier):

Import-Tags –Server $destinationVC –Source C:\vc1_tags.txt

That’s it! You now have the same tag configuration across all your VCs.

Converting your existing custom attributes to tags

What if you are using the legacy custom attributes and want to convert those to tags? The attached ConvertCustomAttributesToTags.ps1 script will do that for you. The script will scan your existing custom attributes and annotation values and based on those create the corresponding tag categories and tags. It will then assign the newly created tags to your inventory items. Using the script is done in the same way as above, download it from here, start PowerCLI, load the script and connect to your vCenter server:

. <path_to_folder>\ ConvertCustomAttributesToTags.ps1

$sourceVC = Connect-VIServer <connection_parameters>

To run the script just call the ConvertCustomAttributesToTags function and pass it the server you want to operate on:

ConvertCustomAttributesToTags $server

Once the function completes you will have tags matching your existing custom attribute hierarchy. If you like you can remove the old custom attributes.


clip_image002[8]This post was created by Dimitar Barfonchovski.Dimitar joined VMware and the PowerCLI team in 2007. He is member of the development part of the team and his main responsibilities are the functional design and implementation of features for the vSphere and vCloud PowerCLI components.

As with all members of the team, he is working to deliver a good and valuable product. He is also working to improve all processes and tools involved in the product development and validation.

This entry was posted in Tags and tagged on by .
Alan Renouf

About Alan Renouf

Alan Renouf is a Product Line Manager at VMware focusing on API's, SDK's and CLI's, He is responsible for providing the architects and operators of private and public cloud infrastructure with the toolkits/frameworks and command-line interfaces they require to build a fully automated software-defined datacenter. Alan is a frequent blogger at http://blogs.vmware.com/PowerCLI a book author and has a personal blog at http://virtu-al.net. You can follow Alan on twitter as @alanrenouf.

20 thoughts on “Using vSphere Tags with PowerCLI

    1. Adib Kozlow

      I am unable to get this to work. I am very new to powerCLI and to CLI in general. I run the script, connect to the server, I don’t know what to do next as Export-Tags isn’t recognized. I am just trying to export the tags from one domain’s vcenter to another domain’s vcenter.

      Any assistance would be great.

      1. Eelco

        There is a difference between the blog post and the ExportImportTags.ps1 script; the script uses Export-Tag and Import-Tag while the blog post mentions Export-Tags and Import-Tags. Notice the extra “s”

        1. Tony

          this simply didn’t work at all. I used the Export-Tag (no ‘S’) and nothing happened. no error, but no result.
          unblock the script
          open PowerCLI 5.5
          set scripts to unrestricted
          navigate to path of extracted script
          run script – \ExportImportTags.ps1
          connect to Server storing in var – $sourceVC = Connect-VIServer
          run Export-Tag function with 2 params. – Export-Tag –Server $sourceVC –Destination C:\vc1_tags.txt == nothing.
          I have full admin rights within vsphere, local system running the script and on VC Server..
          I’ve never met a PS Script that worked as posted, that streak continues here….

          1. Bhavjit

            Rename ExportImportTags.ps1 to ExportImportTags.psm1
            Run “Import module ExportImportTags.psm1”
            $sourceVC = Connect-VIServer
            Export-Tag –Server $sourceVC –Destination vc1_tags.txt
            $destinationVC = Connect-VIServer
            Import-Tags –Server $destinationVC –Source vc1_tags.txt

  1. Pingback: Virtual Spring Cleaning - Organization within vSphere | VMware vSphere Blog - VMware Blogs

  2. Pingback: Virtual Spring Cleaning – Organization within vSphere | Vmware Review

  3. Pingback: vSphere PowerCLI 5.8 SPBM Walkthrough (Part 1): Introduction | VMware vSphere Blog - VMware Blogs

  4. Pingback: Feature: PowerCLI 5.8 r1 - Filtering by Tags | VMware PowerCLI Blog - VMware Blogs

  5. Matt

    Is there a way when running the report for VM’s and their tags to put a comma between each tag to make the report more readable?

    Besides that, awesome article. We are finally getting around to 5.5 and this has helped implement tagging in our environment.

  6. Jason Taylor

    Is a tag assignment assigned to an inventory id? If I remove a Vm from the inventory and then readd it will it lose its tag assignments?

  7. Edward

    I have a question. If there’s a way to export tags, why isn’t there to properly back them up? I just had to re-install my VCenter and lost all tags; I called support and they’re saying that I have to manually type them in – even with a backup/snapshot of my VCenter server these can’t be restored. This makes no sense, and it’s poor thinking from VMware.

  8. Bhavjit

    Follow below sequence to utilize this feature:

    Rename ExportImportTags.ps1 to ExportImportTags.psm1
    Run “Import module ExportImportTags.psm1”
    $sourceVC = Connect-viserver vcenterservername -user domain\user -pass ad343a#
    Export-Tag –Server $sourceVC –Destination vc1_tags.txt
    $destinationVC = Connect-viserver vcenterservername -user domain\user -pass ad343a#
    Import-Tag –Server $destinationVC –Source vc1_tags.txt

    1. Script User for Tags

      Is this supposed to be ran line by line. I still get an error. This is what I am doing.

      1. Extracted ExportImportTags.ps1 from downloaded zip. I then renamed the file to ExportImportTags.psm1
      2. Launch PowerCLI 5.5 (Release 2 Patch 1)
      3. “Import module ExportImportTags.psm1” no output
      4. $sourceVC = Connect-viserver vcenterservername -user domain\user -pass ad343a# I changed the credentials and vcenterservername
      5. Export-Tag –Server $sourceVC –Destination V:\tags\vc1_tags.txt

      I still get the following error.

      Export-Tag : The term ‘Export-Tag’ is not recognized as the name of a cmdlet,
      function, script file, or operable program. Check the spelling of the name, or
      if a path was included, verify that the path is correct and try again.
      At line:1 char:1
      + Export-Tag -Server $sourceVC -Destination v:\tags\vc1_tags.txt
      + ~~~~~~~~~~
      + CategoryInfo : ObjectNotFound: (Export-Tag:String) [], CommandN
      + FullyQualifiedErrorId : CommandNotFoundException

      I am not sure what else I should try?

  9. Pingback: Feature: PowerCLI 5.8 r1 – Filtering by Tags » Brian Graf's Virtualization Blog

  10. pavan

    I am tagging my environemnts now. the isue i am facing is that I need the tag name to be same in both Development and Production environemnt.however they will be tagged to different entities.
    but when i run the New-tagassignment cmdlet it throws an error which says that there are 2 tags with the same name .
    how do i resolve this error.

  11. Pingback: Automatically create custom dynamic groups in vROps as per vCenter Tags – Anything Virtual and Cloudy

Leave a Reply

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