Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Hash Table Grouping

I have a CSV like below:

location,id
loc1,1234
loc1,1235
loc1,1236

Running $a = Import-CSV C:\File.csv | Group-Object "location" I get the following output:

Count  Name    Group
-----  ----    -----
3      loc1    {@{location=loc1; id=1234}, @{location=loc1; id=1235), @{location=loc1, id=1236}}

I would like to add all ID's to a single group (Using Add-QADGroupMember) but I can't figure out how to get a group of ID's for $loc1. It seems to be be grouping them correctly but I can't seem to parse the output into a single group. E.g $loc1 = 1234,1235,1236 that I can loop through.

Any suggestions would be appreciated!

like image 945
user2601449 Avatar asked Oct 29 '25 05:10

user2601449


1 Answers

Group-Object doesn't handle hashtables well, since the keys aren't real properties.

Assuming:

$csv = Import-CSV C:\File.csv

You should be able to do, for example:

$ids = $csv | %{ $_.id }

to get an array of the ID values. You'd probably want to pipe through Get-Unique for location.

If you wanted to get the location for a single ID quickly:

$location = $csv | ?{ $_.id -eq 42 } | %{ $_.location }

If you wanted to get an array of all IDs for a single location quickly (I think this is what you want):

$loc1 = $csv | ?{ $_.location -eq 'loc1' }

For reference, if you wanted to get a hashtable mapping each location to an array of IDs:

$groups = $csv | %{ $_.location } | &{
    begin
    {
        $hash = @{}
    }
    process
    {
        $location = $_.location
        $hash[$location] = $csv | ?{ $_.location -eq $location }
    }
    end
    {
        $hash
    }
}
like image 145
Zenexer Avatar answered Oct 30 '25 21:10

Zenexer