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
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.
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
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically