A script we have developed for creation of the tags for azure VM.   We use an input file to update the tags and as a test, I had done it with upto 7 tags, however, you can have a maximum of 15 tags assigned to the resources in Azure.

This script however, is used to update the Tags for the Virtual Machines.  There is an input file which need to be filled in and kept in the same folder as the script where it is being installed.

The csv file is available for download at the end of this post, please do ensure you rename the file into a .csv extension file

The Main script is below, copy the script into notepad and save it with a .ps1 extension.   Download the input file and rename it with a .csv extension.  Open a PowerShell command window as an Administrator and execute the file.

 #Script for Tag Creation of azure VM
 #Please update the attached CSV for Tag Creation



 $DataSheet = Import-Csv "$currentpath\tagsnew.csv" 
 foreach($data in $DataSheet)
 {
 $SubscriptionName = $data.SubscriptionName
 $ResourceGroupName = $data.ResourceGroupName
 $ServerName = $data.Hostname
 $ResourceType = "Microsoft./virtualMachines"
 Select-AzureRmSubscription -SubscriptionName $SubscriptionName | Out-Null
 $ErrorActionPreference = "Stop"
 try
 {
 #tagcreation
 $tags = @()
 for($i=0;$i -lt 10;$i++) {
 
 $tagname = "tagname" + [string]$i
 $tagvalue = "tagvalue" + [string]$i
 if($data.$tagname) {
 if(($data.$tagname).trim() -ne "") {
 $tags += @( @{ Name=$data.$tagname; Value=$data.$tagvalue })
 }
 }
 }
 #Updating tags in the VM
 $vm= Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $ServerName
 Write-Verbose -Verbose "Adding tags to server $ServerName "
 Update-AzureRmVM -ResourceGroupName $ResourceGroupName -VM $vm <#-ResourceType $ResourceType#> -Tag $tags -ErrorAction Stop 
 }
 catch
 {
 if($_.exception.message -like "*Long running operation failed with status*")
 {}
 else
 {
 write-Host $_.Exception.Message -ForegroundColor Yellow
 continue
 } 
 } 
 }

 

Download

tagsnew.csv_.xls

Leave a Reply

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

Bitnami