I came a cross this blog and created below script to use the {get-tagAssignment -entity (get-vm)} to get and remove tags,
https://virtuallyjason.blogspot.com/2022/02/powercli-and-get-tagassignment.html
This script defines the vCenter server, username, and password as variables, then uses the Connect-VIServer cmdlet with the -Server, -User, and -Password parameters to connect to vCenter using the provided credentials.
It also uses Get-TagAssignment cmdlet to get the tag assignments for a VM and remove those using Remove-TagAssignment cmdlet.
It also writes a message in green for each VM before removing the tags using Write-Host cmdlet and -ForegroundColor parameter.
Make sure that you have the correct path to the csv file in the script and that the csv file contains the VMs names in a column labeled "Name".
=========
# Define the vCenter server, username and password
$vcenterServer = "vcsa.mytest.org"
$username = "administrator@vsphere.local"
$password = "T£stPas$ord"
# Connect to vCenter using username and password
Connect-VIServer -Server $vcenterServer -User $username -Password $password
# Import the list of VMs from a CSV file
$vmList = Import-Csv -Path "vm-list.csv" | Select-Object -ExpandProperty Name
# Loop through the list of VMs and remove all tags
foreach ($vm in $vmList) {
$vm = Get-VM -Name $vm
$tagAssignments = Get-TagAssignment -Entity $vm
foreach ($tagAssignment in $tagAssignments) {
Write-Host "Removing Tag for VM: $vm" -ForegroundColor Green
Remove-TagAssignment -TagAssignment $tagAssignment -Confirm:$false
}
}
# Disconnect from vCenter
Disconnect-VIServer vcsa1.gsslabs.org -Confirm:$false
===========
It's not recommended to hardcode the credentials in the script, A better practice would be to prompt for the credentials or use an encrypted file to read the credentials from.
I recommend to test this script on test environment before using it on production.
No comments:
Post a Comment