title: Powershell LDAP Filter with DirectorySearcher
body: <p>I am using the <code>DirectorySearcher</code> class to find a single user. The criteria should be that the <code>objectCategory</code> is a user, and that his password is <strong>not set to never expires</strong>.</p>
  
  <p>After some searching, I have come up with this:</p>
  
  <pre><code>$searcher = New-Object System.DirectoryServices.DirectorySearcher
  
  $searcher.Filter = "(&amp;(objectCategory=User)(samAccountName=$env:username)(!(userAccountControl:1.2.840.113556.1.4.803:=65536)))"
  </code></pre>
  
  <p>where <code>userAccountControl:1.2.840.113556.1.4.803:=65536</code> should be for users whose password never expires.</p>
  
  <p>Finally I do:</p>
  
  <pre><code>$user = $searcher.FindOne().GetDirectoryEntry()
  </code></pre>
  
  <p>But it says that I cannot call a method on a null-valued expression. I think I am using the parentheses correctly. So then could it be that I can't use the ! operator for this?</p>
  
  <p>Also note that I could use the <code>get-aduser</code> command, like so:</p>
  
  <pre><code>get-aduser -filter * -properties samAccountName, PasswordNeverExpires | where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true"} | where {$_.samAccountName -eq $env:username}
  </code></pre>
  
  <p>but in this instance it would be preferable to use the <code>DirectorySearcher</code> instead like shown above.</p>