Displaying AD groups where a user account is member of?

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

Displaying AD groups where a user account is member of?

Post 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.
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post by jvierra »

To get a canonical name just reference it in your Get".

Get-ADUser -Filter "Name -like '*Administrator*'" -Property CanonicalName
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

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

Post by ITEngineer »

jvierra wrote: Wed Feb 05, 2020 10: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?
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post 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.
User avatar
ITEngineer
Posts: 216
Last visit: Thu Mar 23, 2023 5:45 pm
Has voted: 4 times

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

Post 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'
/* IT Engineer */
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post by jvierra »

Just use Get-AdPrincipalGroupMembership to retrieve the groups belonged to and then filter on the groups you are interested in.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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

Post by jvierra »

This is the template for that:

Code: Select all

Get-ADUser -Filter "Name -like '*Administrator*'" | 
    Get-ADPrincipalGroupMembership | 
    Where{$_.Name -in $groups}
User avatar
Nillth
Posts: 34
Last visit: Mon Oct 30, 2023 10:52 pm
Has voted: 2 times

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

Post 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

This topic is 4 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked