Trix Trix - 2 months ago 15x
PowerShell Question

ADSI/System.DirectoryServices.DirectorySearcher result parsing

A trivial question, but hopefully really obvious for those who know.

Search constructor:

$Search = New-Object System.DirectoryServices.DirectorySearcher
(([adsi]"LDAP://ou=Domain Users,dc=example,dc=pri"),'(objectCategory=person)',

I want to exclude results where the employeeID attribute does not exist.

This works:

$users = $Search.FindAll()
ForEach ($u in $users) {
If ($ {
Write-Host $($

The following does not work - no output. However, when the IF statement is omitted, results are output.

ForEach ($user in $($Search.FindAll())) {
If ($ {
Write-Host $($

Is it a syntax issue in the second example, or do I just need to temporarily store results in an object before running conditional statements on them?

(To circumvent any discussion on why not use the ActiveDirectory module and Get-ADUser, it's for a user that cannot have the module installed on their workstation, nor be granted perms to invoke it via a PSSession on a host where it is installed.)


Just remove if statement and filter search results:

$users = $Search.FindAll() | Where-Object {-not [string]::IsNullOrEmpty($}