0

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

Update: found a slightly nicer way of doing the where clause:

$searcher.FindAll() | where { ($_.properties['employeeid'][0]) }
LeeM
  • 1,118
  • 8
  • 18

1 Answers1

0

Just remove if statement and filter search results:

$users = $Search.FindAll() | Where-Object {-not [string]::IsNullOrEmpty($_.properties.employeeID)}
n01d
  • 1,047
  • 8
  • 22