How to Find Users in a Specific OU Who Aren’t Members of a Group?

0
5
Asked By CleverCactus42 On

I'm working on a PowerShell script to list users in the "Students" organizational unit (OU) who aren't members of a certain group. The current script I'm using returns results from the entire domain instead of just the specific OU. I want to know how to modify it so that it focuses only on the "Students" OU. Here's what I have so far:

$Students = Get-ADUser -Filter * -Properties memberOf
ForEach($User in $Students) {
If(($User.memberOf).length -le 0) { $User | Select Name, memberOf }
}

Any help would be greatly appreciated!

2 Answers

Answered By TechWhiz123 On

Let Active Directory do the heavy lifting for you! If you know the distinguished name (DN) of the group, you can make your script run faster. Here’s how you could set it up:

$groupName = 'someGroup'
$ou = 'OU=Students,DC=example,DC=com'

$adGroup = Get-ADGroup -Identity $groupName
$Students = Get-ADUser -Filter "memberOf -ne '$($adGroup.DistinguishedName)'" -SearchBase $ou

This way, you get a list of users in the "Students" OU who aren't members of that group.

Answered By ScriptingSage89 On

You should definitely use the -SearchBase parameter with Get-ADUser to specify the OU. It lets you narrow down your search right from the start. Also, look into using Get-ADGroupMember if you want to handle group memberships more effectively. Consider using Compare-Object as well for a clearer comparison.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.