How to test from group membership with Powershell

Hi All,

I am using the Quest AD tool in conjuction with powershell to remove users from a group, I need a way to quickly check if a user belongs to the group before issuing the instruction to remove the user from the group.

I need something to return a boolean ideally, in VB you can use ISMember I think, all the powershell examples I have found so far enumerates the group and check if the user is a member, this method will slow my script down big time. If there's nothing that can do it natively in powershell perhaps accessing .NET object via powershell..

Any ideas????

Thanks in advance

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris DentPowerShell DeveloperCommented:

Which do you have a connection to at that point in the script, user or group?

If you've got the user, look at the MemberOf attribute and see if the group exists.

If you have the group, look at Member.

You can use the IsMember method in PowerShell as well. e.g.:

$Group = [ADSI]"LDAP://CN=Domain Admins,CN=Users,DC=domain,DC=com"
$Group.IsMember("LDAP://CN=Some Users,OU=Somewhere,DC=domain,DC=com")

Whether it's fastest depends on what connections you have at that point in the script.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
StevoleeAuthor Commented:
Hi Chris,
I have the connection set to the user can you please
post a sample code for that...

Thx Steve
Chris DentPowerShell DeveloperCommented:

Sure :)

A spot of string comparison should work (even if it is a bit basic), you have to make MemberOf a string first, like this:

$User = Get-QADUser "SomeUser"
If ("$($User.MemberOf)" -Match "SomeGroupName")
  Remove-QADGroupMember "SomeGroupName" -Member $User.DN

Nothing to test that against here, you'll have to do that part I'm afraid.


StevoleeAuthor Commented:
Thanks for the update will test and get back to you...
StevoleeAuthor Commented:
Thanks for the info Chris much appreciated!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.