How to List Users in a Specific OU That Aren’t Part of a Group?

0
19
Asked By CuriousCoder42 On

I'm working on a PowerShell script to list users in the "Students" organizational unit (OU) who are not members of a specific group. The current script I'm using returns users from the entire domain instead of just from that OU. Here's the script I have:

```
$Students = Get-ADUser -Filter * -Properties memberOf

ForEach($User in $Students) {
If(($User.memberOf).length -le 0) { $User | Select Name, memberOf }
}
```

I need guidance on how to modify it correctly to focus specifically on the "Students" OU. Any help would be appreciated!

3 Answers

Answered By TechWhiz99 On

To make your script focus on the specific OU, you should use the `-SearchBase` parameter with `Get-ADUser`. This allows you to target just the OU you're interested in. Here's a quick example:

```
$ou = "OU=Students,DC=yourdomain,DC=com"
$Students = Get-ADUser -Filter * -SearchBase $ou -Properties memberOf

ForEach($User in $Students) {
If(($User.memberOf).Count -eq 0) { $User | Select Name, memberOf }
}
```

This should return only the users in the "Students" OU who aren't members of any group.

ScriptGuru77 -

Great point about using `-SearchBase`! Just remember to check the `Count` property instead of the length for arrays to avoid any unexpected issues with checking for empty groups.

Answered By SimplifiedScripts On

Let AD do some of the heavy lifting for you. If you know the distinguished name of the group already, you can optimize the script further. Here’s a detailed example:

```
$groupName = 'someGroup'
$ou = 'OU=Students,DC=example,DC=com'
$adGroup = Get-ADGroup -Identity $groupName
$Students = Get-ADUser -Filter "memberOf -ne '$($adGroup.DistinguishedName)'" -SearchBase $ou
$Students
```

This should effectively filter your results to just the users you need!

Answered By PowersShellPro On

Another approach is to use `Get-ADGroupMember` to find users not within a certain group. You can compare that against all users in the OU. Here’s how you might do it:

```
$groupName = 'YourGroupName'
$ou = 'OU=Students,DC=yourdomain,DC=com'

# Get the group
$adGroup = Get-ADGroup -Identity $groupName

# Get users not in the group
$Students = Get-ADUser -Filter "memberOf -ne '$($adGroup.DistinguishedName)'" -SearchBase $ou

$Students
```

This will give you a list of users in the "Students" OU who are not part of the specified group.

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.