Migrate Tags from one vCenter to another

When upgrading to vSphere 7 or any other version, you might choose to create a brand new vCenter instead of migrating the old one. But what about folder structure, tags, distributed switches and so on.

Here I will demonstrate how you can easily migrate your tags from one vCenter to another using VMware PowerCLI.

This article assumes that you are already familiar with VMware PowerCLI, and you have the correct access. All execution of scripts involve some risk, and it is your own responsibility to evaluate that risk and clean up after any wrongdoings. I will say that this script should be quite harmless in any installation.

Prerequisites

For this to work you first need to disconnect you hosts from the old vCenter and connect them to the new vCenter, taking care of network connectivity and so on. But you should not remove anything from the old vCenter. The script needs all VM’s to be disconnect, so that it can still query vCenter about them and their tag assignment.

If you do not know how to do this get professional help.

Import-Module VMware.PowerCLI
$global:DefaultVIServers | Disconnect-VIServer -Confirm:$false

$srcVc = "FQDN of Source vCenter"
$dstVc = "FQDN of Destination vCenter"
Connect-VIServer $srcVc
Connect-VIServer $dstVc

$categories = Get-TagCategory -server $srcVc
$tags = get-tag -server $srcVc

foreach ($category in $categories) {
    New-TagCategory -Server $dstVc -Name $category.Name -Description $category.Description -Cardinality $category.Cardinality -EntityType $category.EntityType
}

foreach ($tag in $tags) {
    New-Tag -Server $dstVc -Name $tag.Name -Category $tag.Category.Name -Description $tag.Description
}


$vms = Get-VM -Server $srcVc

foreach ($vm in $vms) {
    $vmName = $vm.Name
    $tags = $vm | Get-TagAssignment
    foreach($tag in $tags) {
        $dstVM = Get-VM -Server $dstVc -Name $vmName | Where-Object {$_.Name -eq $vmName}
        Write-Host "Assigning Tag: $($tag.tag.name) from $vmName to $($dstVM.name)"
        $dstTag = Get-Tag -Server $dstVc -Name $tag.tag.Name
        $dstVM | New-TagAssignment -Tag $dstTag
    }
}

Hope this helps you out. Feel free to leave a comment.

Leave a Reply

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