Home > Software design >  PowerShell script to display users AD groups
PowerShell script to display users AD groups

Time:10-18

I apologise if the question has already been asked.

I am slightly new to PowerShell and I was wondering if you guys could help with creating a PS script to display all AD groups of a specific user e.g. being prompted to enter a username then after pressing enter the AD groups will display then the script will ask for another username.

I have found the command to do this but every time I run the command I would have to change the username each time (very time consuming).

The command is:

(Get-ADUser Username -Properties MemberOf).memberof | Get-ADGroup | Select-Object name

This is probably straight forward to do for an expert in PS but I am struggling here.

Thanks Guys.

CodePudding user response:

Something like this works:

do { 
  write-host -NoNewline "Type username: "
  $user = read-host

  if ($user -eq "") { break }

  (get-aduser $user -Properties memberof).memberof |
    get-adgroup                                    |
    select -exp name
} while ($true)

You could also read usernames from a file and collect the information into a custom data-structure, e.g.:

get-content usernames.txt |
foreach { 
  $groups = (get-aduser $_ -Properties memberof).memberof |
            get-adgroup                                   |
            select -exp name

  [pscustomobject] @{ user = $_; groups = $groups }
}
  • Related