Update-AzureRmTag

I recently had a need of tagging a large number of resources in Azure, and found it difficult to do this easily. So naturally I ended up creating a helper function to do the job for me.

The function takes an array of ResourceIds as input, as well as a hashtable of tags. It will tag all resources with the new tags, without removing any of the old tags.

There are still some small work to be done on the function, such as adding help, confirm/whatif support and some more error handling, but I decided to release it as is for now.

When I get the time to update it, I will update this post. The code is in a gist so it’s possible for anyone to fork and make changes to it. If you want to help contribute to the code, please feel free to fork it and help making it better.


function Update-AzureRmTag {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)]
[string[]] $ResourceId,
[Parameter()]
[hashtable] $Tags = [hashtable]::new()
)
BEGIN {}
PROCESS {
foreach ($resource in $ResourceId) {
try {
$thisResource = Get-AzureRmResource ResourceId $resource
Write-Verbose "Processing $($thisResource.Name)"
if ([bool]($thisResource.Tags.GetEnumerator().Where({$_.Name -notlike '*hidden-link*'}))) {
if ($thisResource.Tags.Count -ne 0) {
[hashtable]$currentTags = $thisResource.Tags
[hashtable]$newTags = $thisResource.Tags + $Tags
}
else {
[hashtable]$newTags = $Tags
}
$result = Set-AzureRmResource ResourceId $thisResource.ResourceId Tag $newTags ErrorAction Stop Force
}
else {
Write-Verbose 'hidden-link found – skipping'
}
}
catch {
Write-Warning "[$($thisResource.Name)] $($_.Exception.Message)"
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s