Search code examples
azurepowershellcsvtags

Grab Azure resources using a list


I am trying to bulk grab Azure resources and change their tags. I have the resource names in a csv file.

$List= Import-Csv "C:\Users\8792.csv"
$Resources = (Get-AzResource | Where-Object {$_.Resource.Name -eq $List})
$Resources.Count
foreach ($resource in $resources){

        #$resource.Name
        $rgtags = $resource.Tags
        #depending on the tag to update, enter the removal value below
        #$rgtags.Remove("DepartmentNumber")
        $rgtags.Remove("Manager")
        $rgtags.Remove("DepartmentNumber")
        $rgtags.Remove("ApplicationName")

        #update tag to be added to resource
        #$rgtags += @{DepartmentNumber = "9r30" }
        $rgtags += @{OwnerEmail = "pita@mail.com" }
    
        Set-AzResource -ResourceId $resource.resourceid -Tag $rgtags -Force -AsJob
}

Nothing happens when I run this code. What am I missing? Is there another way to do this?


Solution

  • Your code has an issue with the $List variable. If you want to check & filter one of the columns in a .csv file, you need to filter $List with a specific column i.e., $List.ResourceName instead of filtering the entire .csv file. Due to this conflict, you couldn't able to retrieve any output.

    There are two ways to modify your code:

    1. Modify for-each loop as below:
    $List= Import-Csv "C:\resourceslist.csv"  
    foreach ($resource  in  $List.ResourceName)
    {
     $resource = Get-AzResource -Name $resource
     $rgtags = $resource.Tags 
     $rgtags.Remove("Manager")           
     $rgtags.Remove("DepartmentNumber") 
     $rgtags += @{OwnerEmail = "pita@mail.com" }
     Set-AzResource -ResourceId $resource.resourceid -Tag $rgtags -Force -AsJob }
    

    Or

    1. As @Santiago Squarzon suggested, Use "-in" $_.Resource.Name -in $List.ResourceName} or "-contains" $_.Resource.Name -contains $List.ResourceName} functions as below:
    $List= Import-Csv "C:\resourceslist.csv"
    $Resources = (Get-AzResource | Where-Object {$_.Resource.Name -contains $List.ResourceName})
    $Resources.Count
    foreach ($resource in $resources){
            $rgtags = $resource.Tags
            $rgtags.Remove("Manager")
            $rgtags.Remove("DepartmentNumber")
            $rgtags += @{OwnerEmail = "pita@mail.com" }
            Set-AzResource -ResourceId $resource.resourceid -Tag $rgtags -Force -AsJob
    }
    

    Output:

    enter image description here

    enter image description here

    Note: You can also update-Aztag PowerShell command to update the tags of Azure resources.