How to save results in multiple CSV?


I have a command like this:

Get-ADUser -LDAPFilter “(name=*)” -SearchScope Subtree `
-SearchBase “OU=Global,DC=PM,DC=Local” | %{
$user = $_
$user | Get-ADPrincipalGroupMembership |
Select @{N=“User”;E={$user.sAMAccountName}},@{N=“Group”;E={$_.Name}}
}| Select User,Group | Export-Csv “C:\Users&wisns\Desktop\blalalala.csv” -nti

It works great for what i want - list all users with all groups they are member of.

But it saves it to one CSV with is a little bit frustrating to read :slight_smile:

Is there way to save results for user in individual file? Something like username.csv and inside a list of groups?

Can you try this?

$users = Get-ADUser -LDAPFilter '(name=*)' -SearchScope Subtree -SearchBase 'Searchbase' 
ForEach ($user in $users) 
  $userInfo = $user |
  Get-ADPrincipalGroupMembership |
  Select-Object -Property @{
    N = 'User'
    E = {
  }, @{
    N = 'Group'
    E = {
  $username = ($userInfo | Select-Object -Unique -Property user).User
  $userInfo  | Export-Csv -Path "D:\$($username).csv" -NoTypeInformation

I tried that before but it create file name “.csv” with is broken. When i change its name file.csv it opens up its the same as before -> username next to grupname in one file/sheet

Now updated the script, you were right, it wasn’t processed properly

Works great :slight_smile: Thanks

You just need to move the export into your loop:

Get-ADUser -LDAPFilter "[name=*]" -SearchScope Subtree `
 -SearchBase "OU=Global,DC=PM,DC=Local" | foreach{
    $user = $_
    $user | 
    Get-ADPrincipalGroupMembership |
    Select @{N="User";E={$user.sAMAccountName}},@{N="Group";E={$_.Name}} |
    Export-Csv ["C:\Users\&wisns\Desktop\{0}.csv" -f $user.SamAccountName] -nti