@Sky High ,
Here is the complete script:
Please Note:
Script was written based upon the below CSV format, if you format is different please modify it accordingly !
$csv = import-csv ".\vmswithtags.csv" #Read all the VMs and their tags to be applied (Please see the format)
$listOfVMsAndTags = @{} #Hashtable to store all the existing VMs & Corresponding Tags which are read from .csv file
foreach($vm in $csv) {
$listOfVMsAndTags.Add($vm.vmname ,$vm.tag)
}
$VMResources = Get-AzVM #Get all the VMs, Resource groupnames
foreach($VMResource in $VMResources)
{
Get existing TAGS
$existingTags = (Get-AzResource -ResourceGroupName $VMResource.ResourceGroupName -Name $VMResource.Name).Tags
Search and find the corresponding tags from the hashtable
$tagsTobeApplied = $listOfVMsAndTags[$VMResource.Name]
Append to existing tags variable
$existingTags += @{$tagsTobeApplied.Split('=')[0]=$tagsTobeApplied.Split('=')1}
Set back the tags
Set-AzResource -ResourceGroupName $VMResource.ResourceGroupName -name $VMResource.ResourceGroupName -ResourceType "Microsoft.Compute/VirtualMachines" -Tag $existingTags
}