Active Directory – PowerShell – Cannot search by null value attributes


If you tried to filter results with any AD cmdlets in PowerShell, you quickly finds out it is not possible with “-Filter” option. For example, I tried to list any user with no Mail attribute value is null:

PS E:> Get-ADUser -Filter { mail -ne $null }
 Get-ADUser : Variable: 'null' found in expression: $null is not defined.
 At line:1 char:1
+ Get-ADUser -Filter { mail -ne $null }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
       + CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
       + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser 

Well, the solution is to use -LDAPFilter instead of -Filter option. Here is the working command:

PS E:> Get-ADUser -LDAPFilter '(!mail=*)' -ResultSetSize 5 -Properties mail | Select-Object Name,Mail
 Name          Mail
 ----          ----
 Josh Doe         
 uvkaseya            
 sg-mcafee          
 Guest             
 IUSR_WEB-SR04     

So the trick is ‘(mail=*)’ filter brings all user accounts with mail account has any value. Adding [NOT] operator in front of mail ‘(!mail=*)’ in the LDAPFilter results with all user accounts with mail attribute is empty.

So use the filter string with any AD property to search like this: -LDAPFilter ‘(!mail=*)’

2 thoughts on “Active Directory – PowerShell – Cannot search by null value attributes

Leave a comment