breich

Get ALL an Account's Group memberships with PowerShell

Dec 5th, 2013
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3.     Gets all the Active Directory groups that have a specified user, computer,
  4.     group, or service account.
  5. .DESCRIPTION
  6.     Gets all the Active Directory groups that have a specified user, computer,
  7.     group, or service account. Unlike the built-in Get-ADPrincipalGroupMembership
  8.     cmtlet, the function I've provided below will perform a recursive search
  9.     that will return all of the groups that the account is a member of through
  10.     membership inheritance. This function required the Active Directory module
  11.     and thus must be run on a domain controller or workstation with Remote Server
  12.     Administration Tools.
  13.  
  14. .PARAMETER dsn
  15.  
  16. The distinguished name (dsn) of the user, computer, group, or service account.
  17.  
  18. .PARAMETER groups
  19.  
  20. An array of ADObject instances for each group in which the user, computer,
  21. group, or service account is a member.  This parameter can be ignored and
  22. in fact should never be specified by the caller. The groups parameter is
  23. used internally to track groups that have already been added to the list
  24. during recursive function calls.
  25.  
  26. .NOTES
  27.     Author     : Brian Reich <breich@reich-consulting.net
  28. .LINK
  29.     http://www.reich-consulting.net
  30. #>
  31. function Get-ADPrincipalGroupMembershipRecursive( ) {
  32.  
  33.     Param(
  34.         [string] $dsn,
  35.         [array]$groups = @()
  36.     )
  37.  
  38.     # Get an ADObject for the account and retrieve memberOf attribute.
  39.     $obj = Get-ADObject $dsn -Properties memberOf
  40.    
  41.     # Iterate through each of the groups in the memberOf attribute.
  42.     foreach( $groupDsn in $obj.memberOf ) {
  43.  
  44.         # Get an ADObject for the current group.
  45.         $tmpGrp = Get-ADObject $groupDsn -Properties memberOf
  46.        
  47.         # Check if the group is already in $groups.
  48.         if( ($groups | where { $_.DistinguishedName -eq $groupDsn }).Count -eq 0 ) {
  49.            
  50.             $groups +=  $tmpGrp
  51.  
  52.             # Go a little deeper by searching this group for more groups.            
  53.             $groups = Get-ADPrincipalGroupMembershipRecursive $groupDsn $groups
  54.         }
  55.     }
  56.  
  57.     return $groups
  58.  
  59. }
  60.  
  61. # Simple Example of how to use the function
  62. $username = Read-Host -Prompt "Enter a username"
  63. $groups   = Get-ADPrincipalGroupMembershipRecursive (Get-ADUser $username).DistinguishedName
  64. $groups | Sort-Object -Property name | Format-Table
Add Comment
Please, Sign In to add comment