nikhileshwar y
nikhileshwar y

Reputation: 51

overwriting tag Name on azure resourcegroup with powershell

Below is the azure resource

PS C:\Windows\System32> Get-AzResource -ResourceGroupName paniRG


Name              : paniavset123
ResourceGroupName : paniRG
ResourceType      : Microsoft.Compute/availabilitySets
Location          : eastus
ResourceId        : /subscriptions/8987b447-d083-481e-9c0f-f2b73a15b18b/resourceGroups/paniRG/providers/Microsoft.C
                    ompute/availabilitySets/paniavset123
Tags              : 
                    Name            Value 
                    ==============  ======
                    CostCenter      ABCDEG
                    Owner           john  
                    classification  Public

From the above output I want to replace Tag Name "classification" with "Classification" and "Public" with "Accounts".

I am following the below procedure to do that.

PS C:\Windows\System32> $tags=@{"Classification"="Accounts"}

PS C:\Windows\System32> $s=Get-AzResource -ResourceGroupName paniRG

PS C:\Windows\System32> Update-AzTag -ResourceId $s.ResourceId -Tag $tags -Operation Merge


Id         : /subscriptions/8987b447-d083-481e-9c0f-f2b73a15b18b/resourceGroups/paniRG/providers/Microsoft.Compute/availabilitySets/
             paniavset123/providers/Microsoft.Resources/tags/default
Name       : default
Type       : Microsoft.Resources/tags
Properties : 
             Name            Value   
             ==============  ========
             CostCenter      ABCDEG  
             Owner           john    
             classification  Accounts

When I use update-aztag command Tag Value is changing but Name its still showing as "classification".

Can anyone please help me on this?

Upvotes: 1

Views: 1407

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You could remove the classification tag from the hash table resource Tags, then add a new Classification tag with the new Account value. You can then modify the newly updated hashtable with Set-AzResource.

$resource = Get-AzResource -Name "RESOURCE NAME" -ResourceGroupName "RESOURCE GROUP NAME"

# Get the tags
$tags = $resource.Tags

# Check if hashtable has classification key
if ($tags.ContainsKey("classification")) {

    # Remove classification key if it exists
    $tags.Remove("classification")
}

# Create Classification tag with Accounts value
$tags.Classification = "Accounts"

# Update resource with new tags
$resource | Set-AzResource -Tag $tags -Force

If you want to use Update-AzTag, you will need to use a Replace operation:

Update-AzTag -ResourceId $s.Id -Tag $tags -Operation Replace

The Merge operation will update the value, but not the key name.

Upvotes: 1

Rajdeep D
Rajdeep D

Reputation: 3910

Just use -Operation Replace not -Operation Merge

Update-AzTag -ResourceId $s.ResourceId -Tag $mergedTags -Operation Replace

Upvotes: 0

Related Questions