How to save results in multiple CSV?

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 1 year, 11 months ago.

  • Author
    Posts
  • #21165

    Hi,

    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 🙂

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

  • #21166
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    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 = {
          $user.sAMAccountName
        }
      }, @{
        N = 'Group'
        E = {
          $_.Name
        }
      }
      $username = ($userInfo | Select-Object -Unique -Property user).User
      $userInfo  | Export-Csv -Path "D:\$($username).csv" -NoTypeInformation
    }
    
  • #21167

    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

  • #21169
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

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

  • #21170

    Works great 🙂 Thanks

  • #21171
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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
    }

You must be logged in to reply to this topic.