Ad group Member validation

Wanted to check if user is a part of an AD group
Script should help to get info for multiple users at once

Below script is not working as its shows do not exists even if the user is a part of the group:

$user = "xxxxxx"
$group = "xxxxxxxxxx"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name

If ($members -contains $user) {
      Write-Host "$user exists in the group"
 } Else {
        Write-Host "$user not exists in the group"
}
Pavan JoshiAsked:
Who is Participating?
 
oBdAConnect With a Mentor Commented:
That probably happens because you're using the Name property, instead of SamAccountName, which must be used in this case.
Try it like that:
$verifyUsers = 'User1', User2', 'User3'
$verifyGroup = 'Group123'

$groupMembers = Get-ADGroupMember $verifyGroup -Recursive | Select-Object -ExpandProperty SamAccountName
Compare-Object -ReferenceObject $verifyUsers -DifferenceObject $groupMembers -IncludeEqual |
	Where-Object {$_.SideIndicator -ne '=>'} |
	Select-Object -Property @{n='GroupName'; e={$verifyGroup}}, @{n='UserName'; e={$_.InputObject}}, @{n='IsMember'; e={$_.SideIndicator -eq '=='}}

Open in new window

2
 
Derek SouterITO Svc Delivery Cons IIICommented:
have you tried simply listing all the members of the group that are returned?    I would suggest that it may be showing username as domain\username - and you are not necessarily checking for that.
1
 
Pavan JoshiAuthor Commented:
For any ID it gives the same result... Even if the user is not a part of that group
0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

 
Pavan JoshiAuthor Commented:
Any other script I can try
0
 
Pavan JoshiAuthor Commented:
Wow, @Obda
It worked but wanted to know if I can use a file as content where all IDs are present and just run the script
0
 
oBdAConnect With a Mentor Commented:
The script doesn't care where the users are coming from.
Assuming you have one SamAccountName per line in a text file, you can just use something like
$verifyUsers = Get-Content -Path 'C:\Temp\users.txt'
# ...

Open in new window

2
 
Pavan JoshiAuthor Commented:
Thanks oBdA
The script works now and I was able to get the output as required.
This is one forum where I get maximum help and I am always thankful to you all :)
0
 
Pavan JoshiAuthor Commented:
Thanks oBdA
The script works now and I was able to get the output as required.
This is one forum where I get maximum help and I am always thankful to you all :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.