Trix Trix - 3 months ago 33
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)',
('name','employeeID'))


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

This works:

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


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

ForEach ($user in $($Search.FindAll())) {
If ($user.properties.employeeID) {
Write-Host $($user.properties.name)
}
}


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.)

Answer

Just remove if statement and filter search results:

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