Get specific tags/values from Get-AzResourceGroup

Dave Gray 586 Reputation points
2021-06-03T12:41:43.273+00:00

Hi

I'm trying (without much luck) to get the values of tags for a specific Azure Resource Group (RG) using Get-AzResourceGroup. At present this is on my laptop using VSCode, however when it is working it will be run from Azure automation / Runbooks. My RG has multiple tags, however the tagI need to check the value for is called "Environment".

This is what I have so far.

# Connect-AzAccount   

Select-AzSubscription -SubscriptionId "###"   
  
$rgs = Get-AzResourceGroup -Name "###"    
  
foreach ($Tag in $rgs.Tags)  
{  
    foreach ($Key in $Tag.Keys)  
    {  
          
        if ($key -eq "environment")  
        {  
            $Key   
            $Key.Length  
            $Tag.Keys  
        }  
    }  
}  

This works insofar as I can filter $key="environment", however I do not know how to get the corresponding value which in this case would be "PROD"

102142-tag.png

If there's a better way to achieve this then please let me know.

Thanks

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,608 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Andreas Baumgarten 116.6K Reputation points MVP
    2021-06-03T15:01:54.903+00:00

    Hi @Dave Gray ,

    maybe this helps:

    $rgName = "xyz"  
    $envName = "Environment"  
    $envValue = "PROD"  
    $tags = Get-AzTag -ResourceId (Get-AzResourceGroup -Name "$rgName").ResourceId  
    $value = $tags.Properties.TagsProperty.$envName  
    # Just some magic  
    if ($value) {  
        if ($value -eq $envValue) {  
            Write-Host "Value $($value.ToUpper()) found in Tag $($envName.ToUpper()) :-)"  
        }  
        else {  
            Write-Output "Value $($envValue.ToUpper()) not found in Tag $($envName.ToUpper()) : Current value is $($value.ToUpper())"  
        }  
    }  
    else {  
        Write-Output "Tag with name $($envName.ToUpper()) not found"  
    }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    2 people found this answer helpful.

  2. Dave Gray 586 Reputation points
    2021-06-05T09:50:24.147+00:00

    Thanks Andreas, I will try that and post back

    0 comments No comments

  3. Ryan Ballanger 0 Reputation points
    2023-07-03T21:03:59.42+00:00

    Here is a one line version:

    (Get-AzResourceGroup).tags.foreach({ $_.Environment})
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.