Page 1 of 1

Displaying AD groups where a user account is member of?

Posted: Wed Feb 05, 2020 9:28 pm
by ITEngineer
People,

I need someone to assist in fixing the logic in my current script below where it should show MemberOf = Yes or True for specific name patterns that is Member of specific sets of AD groups:

Code: Select all

function Get-CanonicalName ([string[]]$DistinguishedName) {    
    foreach ($dn in $DistinguishedName) {      
        $d = $dn.Split(',') ## Split the dn string up into it's constituent parts 
        $arr = (@(($d | Where-Object { $_ -notmatch 'DC=' }) | ForEach-Object { $_.Substring(3) }))  ## get parts excluding the parts relevant to the FQDN and trim off the dn syntax 
        [array]::Reverse($arr)  ## Flip the order of the array. 
 
        ## Create and return the string representation in canonical name format of the supplied DN 
        "{0}/{1}" -f (($d | Where-Object { $_ -match 'dc=' } | ForEach-Object { $_.Replace('DC=', '') }) -join '.'), ($arr -join '/') 
    } 
}

$groups = 'IT Team', 'Production Access', 'Global DL', 'Local Admins'
$users = Get-ADUser -Filter {(Name -like "*Administrator*")}
ForEach ($group in $groups) {
    $members = Get-ADGroupMember -Identity $group | Select-Object -ExpandProperty SamAccountName
                Compare-Object -ReferenceObject $members -DifferenceObject $users -IncludeEqual |
                Where-Object { '==', '=>' -contains $_.SideIndicator } |
                    Select-Object -Property @{n = 'SamAccountName'; e = { Get-CanonicalName($_.InputObject) } }, 
                        @{n = 'GroupName'; e = { $group } }, 
                        @{n = 'MemberOf'; e = { $_.SideIndicator -eq '==' } } | Format-Table -AutoSize
}
The script above always shows MemberOf = False even when the user account Administrator is a member of those AD groups I mentioned.

Re: Displaying AD groups where a user account is member of?

Posted: Wed Feb 05, 2020 11:30 pm
by jvierra
To get a canonical name just reference it in your Get".

Get-ADUser -Filter "Name -like '*Administrator*'" -Property CanonicalName

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 2:13 am
by ITEngineer
jvierra wrote:
Wed Feb 05, 2020 11:30 pm
To get a canonical name just reference it in your Get".

Get-ADUser -Filter "Name -like '*Administrator*'" -Property CanonicalName
OK, that does make sense.

Code: Select all

            @{n = 'MemberOf'; e = { $_.SideIndicator -eq '==' } } | Format-Table -AutoSize
Is there any reason why that section above always displaying false?

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 2:21 am
by jvierra
Because it is never equal.
To begin with I cannot even guess at what you are trying to do. There is almost never any need to use canonicalname. Also you are trying to compare-object with two object collections that can never be matched.

If you take the time to write down a clear statement of what you are trying to do then you will find that coding it will be much easier. The convoluted code tells me that you don't have a clear idea of what you want or how it is to be arrived at.

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 2:24 am
by ITEngineer
OK, what I wanted to achieve is the script to display the AD group, where:
$users = Get-ADUser -Filter {(Name -like "*Administrator*")}

is member of, from these list of AD groups:
$groups = 'IT Team', 'Production Access', 'Global DL', 'Local Admins'

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 2:27 am
by jvierra
Just use Get-AdPrincipalGroupMembership to retrieve the groups belonged to and then filter on the groups you are interested in.

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 2:29 am
by jvierra
This is the template for that:

Code: Select all

Get-ADUser -Filter "Name -like '*Administrator*'" | 
    Get-ADPrincipalGroupMembership | 
    Where{$_.Name -in $groups}

Re: Displaying AD groups where a user account is member of?

Posted: Thu Feb 06, 2020 11:15 pm
by Nillth
try this one out... one additional benefit of this, is that it can be run on any domain joined system without the need to install the AD PowerShell tools, just need appropriate read access to the DC
And should support wild cards on both the user and group values.

Code: Select all

#region Supporting Functions
#https://github.com/Nillth/PWSH-LDAP
function Get-LDAPUser
{
	param
	(
		[string]$cn
	)
	$Filter = "(&(objectCategory=User)(cn=$($cn)))"
	$Searcher = New-Object DirectoryServices.DirectorySearcher
	$Searcher.Filter = $Filter
	$FoundUser = $Searcher.FindAll()

    if ($FoundUser.Count -gt 0){
	$UserEntry = $FoundUser.GetDirectoryEntry()
	return $UserEntry
    }
}
function Get-LDAPGroup
{
	[CmdletBinding(DefaultParameterSetName = 'GroupName')]
	param
	(
		[Parameter(ParameterSetName = 'GroupPrefix')]
		[string]$Prefix,
		[Parameter(ParameterSetName = 'GroupName')]
		[string]$Name
	)
	
	switch ($PSCmdlet.ParameterSetName)
	{
		GroupPrefix{ $Filter = "(&(objectCategory=group)(cn=$Prefix*))" }
		GroupName{ $Filter = "(&(objectCategory=group)(cn=$Name))" }
	}
	
	$Searcher = New-Object DirectoryServices.DirectorySearcher
	$Searcher.Filter = $Filter
	$FoundGroups = $Searcher.FindAll()
	return $FoundGroups
}

function Get-CanonicalName ([string[]]$DistinguishedName)
{
	foreach ($dn in $DistinguishedName)
	{
		$arr = $dn -split ","
		[array]::Reverse($arr)
		$arr = $(($arr | ?{ $_ -match 'dc=' } | %{ $_ -replace 'dc=' }) -join "."), $($(($arr | ?{ $_ -match 'cn=' } | %{ $_ -replace 'cn=', "/" })) -join "") -join ""
		$arr
	}
}
#endregion Supporting Functions


$groups = 'GroupName',"GroupwithWild*","*"
$Users= "Nillth","Bob*","WildUser*","*"

$LDAPUsers = $Users|%{Get-LDAPUser -cn $_;$cn = $_}
$results = ForEach ($group in $groups)
{
	$LDAPGroups = Get-LDAPGroup -Name $group
	foreach ($LDAPGroup in $LDAPGroups)
	{
        if ($null -eq $LDAPGroup.Properties.member){$members = ""}else{
		$members = $LDAPGroup.Properties.member}

        Compare-Object -ReferenceObject $members -DifferenceObject $LDAPUsers.distinguishedName -IncludeEqual |
		Where-Object { '==', '=>' -contains $_.SideIndicator } |
		Select-Object -Property @{ n = 'SamAccountName'; e = { Get-CanonicalName($_.InputObject) } },
					  @{ n = 'GroupName'; e = { $LDAPGroup.Properties.name } },
					  @{ n = 'MemberOf'; e = { $_.SideIndicator -eq '==' } } 
	}
}
$results|Sort-Object -Property "SamAccountName"|Out-GridView