user3208164
user3208164

Reputation: 129

PowerShell sort CSV with multiple items

I am unable to sort a CSV properly. I have data in the following format:

File.csv:

Name,Application
user1,app1
user1,app1
user2,app1
user2,app2

...

I am able to get a list of users with more than one app1, more than one app2, but I cannot figure out how to get a list of users with app1 AND app2.

    $users = Import-Csv file.csv
    $users | ? {$_.Application -eq "app1" | Group Name | ? {$_.Count -gt 1} |
 % {$_ | select -ExpandProperty group | select -first 1}

    $users | ? {$_.Application -eq "app2" | Group Name | ? {$_.Count -gt 1} |
 % {$_ | select -ExpandProperty group | select -first 1}

I'm not even sure on where to start for combining the two.

Upvotes: 0

Views: 130

Answers (2)

user4018458
user4018458

Reputation:

Another approach:

#requires v4.0
$app1='app1'
$app2='app2'

$users | 
    group name | 
    ?{ $_.group.application -eq $app1 } |
    ?{ $_.group.application -eq $app2 } |
    % name

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174575

Group by user name and check that each group contains an entry for each application:

$UsersWithBothApps = $users | Group-Object -Property Name | ForEach-Object {
    $Apps = $_.Group | Select-Object -ExpandProperty Application
    if($Apps -contains "app1" -and $Apps -contains "app2"){
        $_.Name
    }
}

Upvotes: 2

Related Questions