Search code examples
powershellautomationactive-directoryget-aduser

Powershell to read a list Usernames to show the AD group membership of each user and to output this to CSV file


I have a command that will display the AD group membership of a user:

Get-ADPrincipalGroupMembership username | select name

But I have to type each username for every user.

I was wondering if someone could assist me in script where I would provide CSV with list of usernames and to read each user from the file and to output the AD groups the user is part of to CSV file.

UPDATE 1

Guys I have come up with (I know its not the best):

$users = Get-Content -path 'C:\temp\disabledadusersnameaudit.txt'
foreach($user in $users){
write-host "Group Membership for: " $user
Get-ADPrincipalGroupMembership -Identity $user | Select name | ft -hidetableheaders
}

But getting this error message:

Get-ADPrincipalGroupMembership : An unspecified error has occurred
At line:4 char:1
+ Get-ADPrincipalGroupMembership -Identity $user | Select name | ft -hidetablehead ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (SSmall:ADPrincipal) [Get-ADPrincipalGroupMembership], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADPrincipalGroupMembership

UPDATE 2

Managed to find script from a previous answer:

How to get multiple users membership groups from AD using Powershell script?

$userlist = Get-Content 'C:\temp\disabledadusersnameaudit.txt'

Get-ADUser -Filter '*' -Properties memberof | Where-Object {
  $userlist -contains $_.SamAccountName
} | ForEach-Object {
  $username = $_
  $groups = $_ | Select-Object -Expand memberof |
            ForEach-Object { (Get-ADGroup $_).Name }
  "{0}: {1}" -f $username, ($groups -join ', ')
} | Out-File 'c:\temp\Audit.csv'

This works but 2 issues here the audit CSV looks like this:

Audit CSV Result

All the AD groups are in one column would need to separate them via the , I guess as delimiter?

The other issue is I would like to state the username it would unable to find in the audit too.

UPDATE 3

@Santiago I ran you script and got this via the PS screen:

WARNING: Cannot find an object with identity: 'Username1' under: 'DC=my,DC=domain,DC=net'.
WARNING: The search filter cannot be recognized
WARNING: Cannot find an object with identity: 'Username2' under: 'DC=my,DC=domain,DC=net'.
WARNING: Cannot find an object with identity: 'Username3' under: 'DC=my,DC=domain,DC=net'.
WARNING: The search filter cannot be recognized

Identifies the users it can't find but not working for the user it can find state "WARNING: The search filter cannot be recognized"

UPDATE 4

Making progress now.

User                                                               Membership                                                        
----                                                               ----------                                                        
Username1                                                                                                                             
WARNING: Cannot find an object with identity: 'Username2' under: 'DC=my,DC=domain,DC=net'.
WARNING: Cannot find an object with identity: 'Username3' under: 'DC=my,DC=domain,DC=net'.
WARNING: Cannot find an object with identity: 'Username4' under: 'DC=my,DC=domain,DC=net'.
Username5     

The usernames it can find but is not showing the AD groups? Showing as blank

UPDATE 5

Getting there:

User                                                               Membership                                                        
----                                                               ----------                                                        
Username1                                                           AD GroupName1, AD GroupName2, AD GroupName3, AD GroupName4, AD Group...
WARNING: Cannot find an object with identity: 'Username2' under: 'DC=my,DC=domain,DC=net'.
WARNING: Cannot find an object with identity: 'Username3' under: 'DC=my,DC=domain,DC=net'.
WARNING: Cannot find an object with identity: 'Username4' under: 'DC=my,DC=domain,DC=net'.
Username5                                                           AD GroupName1, AD GroupName2, AD GroupName3, AD GroupName4

When a user has a lot of AD group it doesn't show all of the group this is on the ... (3 full stop/periods) I guess this is due to the amount of characters it can output - 2 questions of improvement.

First is it possible when outputting to CSV will it still show as ... or will it have the full AD groups the user is part off?

Second is when the user is not found instead of:

WARNING: Cannot find an object with identity: 'Username2' under: 'DC=my,DC=domain,DC=net'.

Could it echo '$User is not in the domain!' as this would much better.

Thanks again for the help Santiago!


Solution

  • I don't have an explanation for the error you have shown in your question but also Get-ADPrincipalGroupMembership is known to be buggy. I would recommend querying the user first to get their DistinguishedName and from there you can query all groups having this user as a member:

    Get-Content -Path 'C:\temp\disabledadusersnameaudit.txt' | ForEach-Object {
        try {
            $user = Get-ADUser $_
            $membership = Get-ADGroup -LDAPFilter "(member=$($user.DistinguishedName))"
    
            [pscustomobject]@{
                User       = $user.samAccountName
                Membership = $membership.samAccountName -join ', '
            }
        }
        catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
            [pscustomobject]@{
                User       = "'$($_.TargetObject)' could not be found in Domain."
                Membership = $null
            }
        }
        catch {
            Write-Warning $_
        }
    } | Export-Csv .....path.csv -NoTypeInformation