Export multiple outputs within foreach

Viewed 109

I'm looking to export some data, in particular an AD user along with their AD groups.

My current code:

$users = import-csv -path C:\path

    foreach ($user in $users) {
    $user | select name,SamAccountName | ft
    Get-ADPrincipalGroupMembership $user.samaccountname | select name
    #export-csv -path C:\path-NoTypeInformation -Append
}

The issue i'm having is whenever I try to export this information i'm only exporting the group output whereas I need the username to see who these groups actually belong to.

Perhaps there's a better method to achieve this?

1 Answers

You may want to use Select-Object to sort of "bind" the information together with a couple of calculated properties referencing the current $user's properties:

foreach ($user in $users) {
    Get-ADPrincipalGroupMembership $user.samaccountname |Select Name,@{Name='User';Expression={$user.Name}},@{Name='SAMAccountName';Expression={$user.SAMAccountName}} |Export-Csv -Path C:\path -NoTypeInformation -Append
}

If you want to group the output in the shell by user name but only display the group name, you can use Format-Table Name -GroupBy User:

# collect the information
$groupMemberships = foreach ($user in $users) {
    Get-ADPrincipalGroupMembership $user.samaccountname |Select Name,@{Name='User';Expression={$user.Name}},@{Name='SAMAccountName';Expression={$user.SAMAccountName}}
}

# format console output 
$groupMemberships |Format-Table Name -GroupBy User

# export
$groupMemberships |Export-Csv -Path C:\path -NoTypeInformation -Append
Related