How to list AD group membership for AD users using input list?

Martin_K picture Martin_K · Jan 20, 2014 · Viewed 149.2k times · Source

I'm fairly new PS user... Looking for some assistance with a powershell script to obtain list of security groups user is member of.

To describe what I need:

  • I have input list (txt file) with many users (samaccountnames). Every name is on a new line.
  • I need the script to search these names in AD - whole forest, not just one single domain
  • output should look like "samaccountname" and list of groups this account is member of in one line, so I can sort it in excel

This is the script I have:

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

ForEach ($User in $users) {
  $getmembership = Get-ADUser $User.Users -Properties MemberOf | Select -ExpandProperty memberof
  $getmembership | Out-File -Append c:\membership.txt 
}

but it throws me an error:

Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument and try the command again.
At line:4 char:28
+ $getmembership = Get-ADUser <<<<  $User.Users -Properties MemberOf | Select -ExpandProperty memberof
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Anyway, this script wouldn't search the whole forest.

Sample input list:

username1
username2
username3
username4... etc

Sample output list

username1;group1;group2;group3
username2;group1;group2;group3;group4... etc or something similar

Any help would be greatly appreciated.

Answer

Trevor Sullivan picture Trevor Sullivan · Jan 20, 2014

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;