Construct Three value Hashtable from CSV in Powershell

Rajaniesh Kaushikk 201 Reputation points MVP
2021-05-11T21:55:03.727+00:00

Hi,

I am using this code to tag the Azure resources. But instead of hardcoding the key Values like this I want to pick the key values from a csv file. How can we achieve it

$tags = @{"key"="value"}
$csv = import-csv "C:\tags\tags.csv"

$csv | ForEach-Object {
Write-Host " $($.Name), $($.RESOURCE_GROUP), $($_.SUBSCRIPTION_ID ) "
Set-AzContext -Subscription $_.subscription_ID

$resource = Get-AzResource -Name $.Name -ResourceGroup $.RESOURCE_GROUP
Update-AzTag -ResourceId $resource.id -Tag $tags -Operation Merge
}

Regards
Rajaniesh

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

5 answers

Sort by: Most helpful
  1. Anonymous
    2021-05-12T02:58:40.927+00:00

    Hi,

    Assuming the csv file has two columns with the headers "key" and "value", you write the key/value pairs to a hashtable like below

    $file = "C:\temp\hashtable.csv"  
    $tags = @{}  
    Import-Csv -Path $file |ForEach-Object{  
        $tags.Add($_.key,$_.value)  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Rajaniesh Kaushikk 201 Reputation points MVP
    2021-05-12T10:53:48.727+00:00

    This will never work you can try on your own. This will not add the =sign. I already tried it before posting it in this forum.


  3. Rajaniesh Kaushikk 201 Reputation points MVP
    2021-05-14T02:53:20.323+00:00

    I tried running your code and it does not work here is the output. It keep on asking the parameters.96529-issue.jpg


  4. Rajaniesh Kaushikk 201 Reputation points MVP
    2021-05-14T03:06:42.473+00:00

    I did some more research and found this code to be working

    # Constants.
    $DELIM = ','
    $CSV_F = 'C:\tags\tags.csv'
    
    # Parse keys
    $keys = (gc "${CSV_F}" -TotalCount 1).Split($DELIM)
    $csv = Import-CSV "${CSV_F}"
     $TagsHashTable=@{}
    
    # Iterate through CSV to build array of hashtables.
    ForEach ($r in $csv) {
        $tmp_h = @{}
    
        # Create hash of key-value pairs.
        ForEach($k in $keys) {
            $tmp_h[$k] = $r.($k)
        }
    
        # Add hash to array of hashes.
        $TagsHashTable += $tmp_h
    }
    
    0 comments No comments

  5. Rajaniesh Kaushikk 201 Reputation points MVP
    2021-05-14T10:53:44.757+00:00

    Even if you move it at the same line it won't work.

    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.