none
Retrieve name, membership and department from AD with PowerShell? RRS feed

  • Question

  • Hi,

    I found a script (I'm not great with it) that retrieves the group membership for all users in our Active Directory, however, I'd also like add a field for retrieving the department that each user belongs to. Would this be possible, and if so, how? If you have an answer and the time I'd also appriciate an explanation so I can learn (I couldn't quite get it to work on my own).

    The working script for which I'd like to add Department-variable to:

    Import-Module ActiveDirectory
    $Users = ForEach ($U in (Get-ADUser -Filter {Enabled -eq "True"}))
    { 
    	$UN = Get-ADUser $U -Properties MemberOf
    	$Groups = ForEach ($Group in ($UN.MemberOf))
    	{
    		(Get-ADGroup $Group).Name
    	}
    	$Groups = $Groups | Sort
    	ForEach ($Group in $Groups)
    	{
    		New-Object PSObject -Property @{
    		Name = $UN.Name
    		Group = $Group
    		}
    	}
    }
    $Users | Export-CSV C:\UserMemberships.csv

    Kindly,

    Joni

    Friday, July 28, 2017 2:24 PM

Answers

  • The department is not returned by default in Get-ADUser

    try changing

    $UN = Get-ADUser $U -Properties MemberOf

    to

    $UN = Get-ADUser $U -Properties MemberOf,department

    • Marked as answer by JoniSPL Monday, July 31, 2017 11:40 AM
    Friday, July 28, 2017 2:41 PM
  • then your group would be

    ForEach ($Group in $Groups) { New-Object PSObject -Property @{ Name = $UN.Name

    Department = $Un.Department Group = $Group } }


    • Edited by simbrook2 Friday, July 28, 2017 2:43 PM
    • Marked as answer by JoniSPL Monday, July 31, 2017 11:40 AM
    Friday, July 28, 2017 2:43 PM

All replies