powershellcsvactive-directoryactivedirectorymembership

How to pipe "member of" to csv in Powershell


I am attempting to get a list of information about what groups a selected user is a member of. I found a script on here earlier that seemed to be of use:

    Get-ADUser -SearchBase "OU=Users,DC=Domain,DC=Local" -Filter *  |  foreach-object {
        write-host "User:" $_.Name -foreground green
        Get-ADPrincipalGroupMembership $_.SamAccountName |  foreach-object {
        write-host "Member Of:" $_.name
        } 
    }

However this script is not doing the job. I need to take the data gathered from this script and export to a CSV. I have attempted to pipeline Export-Csv in various places through the script (last curly bracket, second to last curly bracket, and before the curly brackets) but I'm met with no success.

Any other ideas? I attempted another script that I wrote:

Get-ADPrincipalGroupMembership -Filter * -SearchBase "OU=Users,DC=Domain,DC=Local"
-Properties name,SamAccountName | select name,SamAccountName | Export-Csv "C:\Path.csv"

And this one as well

    Get-ADUser -Filter * -SearchBase "OU=Users,DC=Domain,DC=Local" -Properties name,SamAccountName | select name,SamAccountName | Export-Csv "C:\Path.csv"

Neither of which was successful.


Solution

  • I'm not sure how you intend on the final CSV to be formatted. In the first code you are using "write-host" which will only write that content to the screen. You may want to take each of those and pipe them into a csv manually. Using your code here is an example.

    "`"User`",`"Group`"" | out-file export.csv
    
        Get-ADUser -SearchBase "CN=Users,DC=domain,DC=local" -Filter *  |  foreach-object {
            write-host "User:" $_.Name -foreground green
            $u = $_.samaccountName
            Get-ADPrincipalGroupMembership $_.SamAccountName |  foreach-object {
            write-host "Member Of:" $_.name
            $g = $_.name
            "`"$u`",`"$g`"" | out-file export.csv -append
            } 
        }