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=*)’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s