How to Filter Users in PowerShell Based on Multiple Conditions?

0
1
Asked By CuriousCoder42 On

I'm having trouble filtering users based on more than three fields using PowerShell. My current script adds users to a group based on three conditions: homephone, employeetype, and mobilephone. The conditions I'm using are homephone -eq 'txt', employeetype -eq 'txt', and mobilephone -ne 'txt'. However, I'm confused about how to structure the $AddFilter in brackets for these conditions. Also, I'm unsure how to handle cases where the mobilephone field isn't used. Here's the part of my script I need help with:
```
$AddFilter = "homePhone -eq '$Building' -And employeeType -eq 'A' -And mobilephone -ne 'SKIP'"
$AddUsers = Get-ADUser -Filter $AddFilter
if ($AddUsers) {
Add-ADGroupMember -Identity $Group -members $AddUsers -Confirm:$false
}
```
It works fine in general, but I need to create an exception for when mobilephone is 'SKIP'. Any advice or suggestions would be appreciated!

3 Answers

Answered By CodeNinja88 On

Your syntax looks correct, but I've had better luck using 'mobile' instead of 'mobilephone'. Here's another approach that works for me:
```
$group = Get-ADGroup $group
$building = 'phonenumber'
$employeeType = 'A'
$ldapFilter = '(&&(homePhone={0})(EmployeeType={1})(memberof={2})(!(mobile=skip)))' -f $Building, $employeeType, $adGroup.DistinguishedName
Get-ADUser -LDAPFilter $ldapFilter
```
Give 'mobile' a shot and let us know how it goes!

Answered By TechWizard77 On

If your Active Directory isn't too large (maybe fewer than 5,000 users), I recommend using the PowerShell filter instead of an AD filter. It's straightforward, although it might be a little slower. By the way, you might be mistaken about the attribute name; it should probably be `mobile`, not `Mobilephone`. Here's a quick example:
```
$AllUsers = Get-ADUser
$ADUsers = $AllUsers | Where-Object { $_.HomePhone -eq $Building -and $_.EmployeeType -eq 'A' -and (-not $_.Mobile) }
```
This way, you'll effectively filter out users with a 'SKIP' in their mobile field.

Answered By ScriptingGuru99 On

If you're frequently applying complex filters, consider using an LDAP filter. But if it doesn't come up often, it's fine to pass a simple filter to `Get-ADUser`, which eliminates the most unwanted accounts, and then use `Where-Object` for refining the results. It might be slower but is more readable compared to LDAP filters.

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.