2

Is there any way I can import a list of users, get their groups in AD and export the list?

Import-Csv C:\Users.csv |
  % {Get-AdUser -filter "displayname -eq '$($_.username)'"} |
    Get-ADprincipalGroupMembership |
      Select samaccountname, name |
        Export-csv -path C:\UserPermiss.csv -NoTypeInformation

File example:

username
Jon Jo
Steve Price
Alan Partridge

Cheers.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Mike
  • 67
  • 1
  • 2
  • 11

2 Answers2

3

You could use the memberof property and then join the array of groups inside a calculated property.

Import-Csv C:\Users.csv | 
    ForEach-Object{
        Get-AdUser -Filter "displayname -eq '$($_.username)'" -Properties memberof
    } |
    Select-Object samaccountname, name, @{n='memberof';e={$_.memberof -join ';'}} |
    Export-Csv -Path C:\UserPermiss.csv -NoTypeInformation
BenH
  • 9,766
  • 1
  • 22
  • 35
  • Hi BenH, Thanks for that, would it be possible to pull back just the group name? (and username) – Mike Jun 15 '18 at 22:07
  • @BenH How come this code is skipping some of my users and how can i use -Get-ADPrincipalGroupMembership -Identity username – lisa_rao007 Feb 19 '20 at 20:02
3

In PSv4+ you can leverage the -PipelineVariable / -pv common parameter to make the output of an earlier pipeline stage available to script blocks used in later pipeline stages:

Import-Csv C:\Users.csv |
  ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)'"} |
    Get-ADprincipalGroupMembership |
      Select-Object @{ n = 'samaccountname'; e = { $user.samaccountname } }, name |
        Export-csv -path C:\UserPermiss.csv -NoTypeInformation

Using -pv user makes the AD user output by Get-AdUser available as variable $user in the Select-Object stage, where it is referenced in the script block of calculated property samaccountname, pairing the name of the AD user at hand with the name of each AD group they are a member of.

The resulting CSV file would look something like this:

"samaccountname","name"
"jjo","group1"
"jjo","group2"
"sprice","group1"
"sprice","group3"
"sprice","group4"
# ...
mklement0
  • 382,024
  • 64
  • 607
  • 775