Home > Blockchain >  query powershell to pull users from a list and return all of their groups to a file
query powershell to pull users from a list and return all of their groups to a file

Time:09-01

I have a list of 800 users that I would like to get a list of each user's AD groups and then output the user's name(samAccountName in my file) and their groups to a file. I have tried the following code, but it does not put the Account name, and is not parsing all of the entries in the file - I have 9 entries, I get a text file with 5 groupings of groups. The code I am using:

$users = Get-Content C:\scripts\vendors.txt

ForEach ($User in $users) {
  Get-ADPrincipalGroupMembership $user | select $user.samaccountname |Select Name | Sort Name | ft @{L='Current Groups';E={$PSItem.Name}} -AutoSize | Out-File  -append c:\scripts\vendorlog.txt 
}

CodePudding user response:

You already know how to get a user's membership via Get-ADPrincipalGroupMembership, seems like you only need help with enumerating each group and then merging that output with the user being processed, for that you can use PSCustomObject to instantiate and output new objects, then that output can be captured and exported to CSV with Export-Csv.

Get-Content C:\scripts\vendors.txt | ForEach-Object {
    try {
        foreach($group in Get-ADPrincipalGroupMembership $_) {
            [pscustomobject]@{
                UserName = $_
                MemberOf = $group.Name
            }
        }
    }
    catch {
        Write-Warning $_
    }
} | Export-Csv path/to/myExport.csv -NoTypeInformation
  • Related