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
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!
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.
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
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
[Centos] Delete All Files And Folders That Contain a String