In grown environments it often comes to a complete confusion. Employees in departments are group members in groups in which they should not be member of.
If there is a clean and tidy Active Directory environment, then you can use the database perfectly for queries. For example, if the name of the department is in the department field, the group membership of this user can be queried. This article introduces an Advanced Function and allows you to query the group membership per department.
The Active Director Department Attribut
What I’m talking about is this:
Let’s move on with the examples of my function.
Get-ADGroupMembershipperDepartment
This advanced function can be implemented in your PowerShell environment. More about this in the last part.
The command in action. It shows all users of the given department and their group memberships, including the nested groups.
Only one parameter defined: Department. At the end you’ll be asked to print this. Make sure a default printer is installed on your system.
The Function
function Get-ADGroupMembershipperDepartment { [CmdletBinding()] param ( [Parameter(Position=0)] [String]$Department ) $user=Get-ADUser -filter {department -eq $Department} -Properties name,department $result=@() foreach ($u in $user) { $userdn = $u.DistinguishedName $Nested = "(member:1.2.840.113556.1.4.1941:=$userdn)" $a=Get-ADGroup -LDAPFilter $Nested -ResultPageSize 1000 $x=($a.Name) -join "`r`n" $result+=New-Object -TypeName PSObject -Property ([ordered]@{ 'User'=$u.Name 'Department'=$u.department 'Groups'=$x }) } $result | Format-Table -AutoSize -Wrap $read=Read-Host -Prompt 'Do you want to print this? (Y/N)' If ($read -eq 'Y') {$result | Format-Table -AutoSize -Wrap | Out-Printer} }
If you like it, make it permanent.
Make it permanent
If you like my approach open PowerShell ISE. Copy the function into your ISE session. Create a folder in C:\Program Files\Windows PowerShell\Modules and save the code as psm1 file. Make sure that your file name and folder name match.
From now on, PowerShell will load the custom module each time PowerShell is started.
Acknowledgement
Many thanks to the great guys helped me out of my disaster with nested groups on technet. Special thanks to Richard Mueller for his post that helped me so much.
Categories: PowerShell, Windows Server