If you want all the groups for a given user on the same line as the username, you could do something like this:
foreach ($suser in (Get-ADUser -Filter {samaccountname -like "m*"})) {
$user = $suser.SamAccountName
$groups = Get-ADPrincipalGroupMembership -Identity $user |
Select-Object -Expand SamAccountName
'{0},{1}' -f $user, ($groups -join ',') | Out-File $file -Append
}
or like this (using the pipeline):
Get-ADUser -Filter {samaccountname -like "m*"} | ForEach-Object {
$groups = Get-ADPrincipalGroupMembership -Identity $_.SamAccountName |
Select-Object -Expand SamAccountName
'{0},{1}' -f $_.SamAccountName, ($groups -join ',')
} | Out-File $file
source
share