Reputation: 249
I am using the DirectorySearcher
class to find a single user. The criteria should be that the objectCategory
is a user, and that his password is not set to never expires.
After some searching, I have come up with this:
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.Filter = "(&(objectCategory=User)(samAccountName=$env:username)(!(userAccountControl:1.2.840.113556.1.4.803:=65536)))"
where userAccountControl:1.2.840.113556.1.4.803:=65536
should be for users whose password never expires.
Finally I do:
$user = $searcher.FindOne().GetDirectoryEntry()
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?
Also note that I could use the get-aduser
command, like so:
get-aduser -filter * -properties samAccountName, PasswordNeverExpires | where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true"} | where {$_.samAccountName -eq $env:username}
but in this instance it would be preferable to use the DirectorySearcher
instead like shown above.
Upvotes: 3
Views: 3295
Reputation: 72610
In fact your code is working, but when the $searcher.FindOne(
) return nothing, that is to say, when the filter return nothing, the GetDirectoryEntry()
method give :
> You cannot call a method on a null-valued expression. At line:1 char:1 > + $searcher.FindOne().GetDirectoryEntry() > + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > + CategoryInfo : InvalidOperation: (:) [], RuntimeException > + FullyQualifiedErrorId : InvokeMethodOnNull
Try :
$user = $searcher.FindOne()
if($user -ne $null) {$user.GetDirectoryEntry()} else {write-host "Niet"}
Upvotes: 1