My code:
$csv = "C:\Downloads\a.csv"
$category = "environment"
$Tag = "critical"
$CMDBInfo = Import-CSV "$csv"
ForEach ($item in $CMDBInfo)
{
$Name = $item.Name
Write-Host ".... Assigning tag "$Tag" in Category "$category" to VM "$Name" "
$vm = Get-VM -Name $Name
Get-TagAssignment -Entity $vm -Server (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) | where{$_.Tag.Category -eq $category} | Remove-TagAssignment -Confirm:$false
New-TagAssignment -Entity $vm -Tag $Tag -Server (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) | Out-Null
}
Resultant error makes me think the Remove operation is failing:
.... Assigning tag critical in Category environment to VM OITAutomate01
New-TagAssignment : 4/29/2020 1:17:45 PM New-TagAssignment Tag urn:vmomi:InventoryServiceTag:8a67c817-523f-47ba-89a1-c34cd8766b52:GLOBAL
is ineligible to
attach to urn:vmomi:VirtualMachine:vm-484555:a79327f1-40fe-40af-aeca-58dd99c92331 because of a cardinality violation.
At D:\ECE\vCenter\tested\a1.ps1:20 char:6
+ New-TagAssignment -Entity $vm -Tag $Tag -Server (([uri]$vm.Exten ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-TagAssignment], CisException
+ FullyQualifiedErrorId : ViCore.Impl.V1.Service.Tagging.Cis.TaggingServiceCisImpl.CheckBatchResult.Error,VMware.VimAutomation.ViCore.Cmdlets.Commands.T
agging.NewTagAssignment
Try with $_.Tag.Category.Name
Not sure why you have the Server parameter on the Get-TagAssignment cmdlet.
Are you connected to multiple vCenters?If not, just leave it out
Get-TagAssignment -Entity $vm | where{$_.Tag.Category.Name -eq $category} | Remove-TagAssignment -Confirm:$false
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference