Skip to content

Instantly share code, notes, and snippets.

@rcabr
Created June 11, 2018 15:12
Show Gist options
  • Save rcabr/735141366ac57ca11a65cf1d72dcdc2f to your computer and use it in GitHub Desktop.
Save rcabr/735141366ac57ca11a65cf1d72dcdc2f to your computer and use it in GitHub Desktop.
Azure Powershell to apply two tags (appId, environment) to all resources in the specified resource group
# Applies these two tags (appId, environment) to all resources in the specified resource group.
# Optional: resourcePattern will be used to select a subset of resources to apply tags to.
[CmdletBinding()]
param(
[string] $resourceGroupName,
[string] $appIdValue,
[string] $environmentValue,
[string] $resourcePattern = ""
)
$excludedResourceTypes = @("Microsoft.Compute/virtualMachines/extensions", "Microsoft.Compute/restorePointCollections")
$resources = Get-AzureRmResource | Where-Object {$_.ResourceGroupName -eq $resourceGroupName} | Where-Object { $excludedResourceTypes -notcontains $_.ResourceType}
if ($resourcePattern -ne "")
{
$resources = $resources | Where-Object { $_.Name -like $resourcePattern }
}
$resources | ForEach-Object {
Write-Host ("Updating resource: " + $_.Name + " Type "+ $_.ResourceType)
$isChanged = $false
$tags = $_.Tags
if ($tags -eq $null)
{
$tags = @{}
}
if ($tags.ContainsKey("appIdOrProjectName"))
{
$isChanged = $tags["appIdOrProjectName"] -ne $appIdValue
}
else
{
$isChanged = $true
}
if ($tags.ContainsKey("environment"))
{
$isChanged = $isChanged -or ($tags["environment"] -ne $environmentValue)
}
else
{
$isChanged = $true
}
if (-not $isChanged) {
Write-Host "No changed tags. Not updating."
}
else
{
$tags.Remove("appIdOrProjectName");
$tags.Remove("environment");
$tags += @{appIdOrProjectName = $appIdValue}
$tags += @{environment = $environmentValue}
Set-AzureRmResource -Tag $tags -ResourceId $_.ResourceId -Force
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment