Public/ps1/Set-VMTagReplacement.ps1

<#
.Synopsis
    Replaces an old tag with a new one on all VMs in a specified category within a VMware vCenter.
 
.Description
    The Set-VMTagReplacement function replaces an old tag with a new one on all VMs that have the old tag assigned, within a given tag category. It ensures that the new tag is created if it does not already exist, then updates the tag assignments for the VMs. This function requires that the user is already connected to the vCenter.
 
.Parameter OldTagName
    Specifies the name of the old tag to be replaced. This tag must exist in the specified category.
 
.Parameter OldTagCategory
    Specifies the category within which the old tag is located. This category must exist in vCenter.
 
.Parameter NewTagName
    Specifies the name of the new tag to assign to the VMs. If this tag does not exist, it will be created.
 
.Parameter NewTagCategory
    Specifies the category within which the new tag will be located. This category must exist in vCenter.
 
.Example
    Set-VMTagReplacement -OldTagName "OldTag" -OldTagCategory "Category1" -NewTagName "NewTag" -NewTagCategory "Category2"
    This example replaces the 'OldTag' tag with 'NewTag' in the 'Category1' category on all VMs that have the 'OldTag' tag assigned, moving the new tag to 'Category2'.
 
.Notes
    Author: bensiegit
    Version: 1.0.0
 
T his script requires VMware PowerCLI to be installed and that the user running the script has sufficient permissions to manage tags and VMs in vCenter. It is recommended to test the script in a non-production environment before running it in production.
#>

function Set-VMTagReplacement {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$OldTagName,

        [Parameter(Mandatory=$true)]
        [string]$OldTagCategory,

        [Parameter(Mandatory=$true)]
        [string]$NewTagName,

        [Parameter(Mandatory=$true)]
        [string]$NewTagCategory
    )

    try {
        # Retrieve the old tag object
        $oldTag = Get-Tag -Name $OldTagName -Category $OldTagCategory -ErrorAction Stop

        # Check if new tag exists in its respective category, if not, create it
        $newTag = Get-Tag -Name $NewTagName -Category $NewTagCategory -ErrorAction SilentlyContinue
        if (-not $newTag) {
            $newTag = New-Tag -Name $NewTagName -Category $NewTagCategory
        }

        # Get all VMs with the old tag
        $vms = Get-VM -Tag $oldTag

        # Loop over each VM and replace tags
        foreach ($vm in $vms) {
            $tagAssignment = Get-TagAssignment -Entity $vm -Category $OldTagCategory -Tag $oldTag
            Remove-TagAssignment -TagAssignment $tagAssignment -Confirm:$false
            New-TagAssignment -Tag $newTag -Entity $vm
        }
    }
    catch {
        Write-Error "An error occurred: $_"
    }
}