Search code examples
windowspowershellactive-directoryget-aduser

Get-AdUser Lookup for each user in csv list with LDAPFilter anr match


I'm querying AD for user details using a list of usernames derived from a different list meaning that not all usernames match the SamAccountName exactly e.g. might have a number or letter dropped from the end. I can get the exact match lookup to work and output the names it can't find but I'd like to take that list names and run them through an LDAPFilter anr search to check for fuzzy matches as well. So far I have:

ForEach($User in $List){
Write-host "Now checking $User"

Try{
     Get-ADUser -LDAPFilter "(anr=$User)" -Properties * | 
     select-object DisplayName,UserPrincipalName,mail,Enabled | 
     Export-CSV -Append $OutputFileResults -NoTypeInformation
     Write-host "$User found successfully" -foregroundcolor Green
     }
Catch{
    $User | Export-CSV -Append $OutputFileFailed -NoTypeInformation
    Write-host "$User not found" -foregroundcolor Red
    }
}

At the moment the output I get just says that the username was found successfully but writes nothing into the output file.


Solution

  • Get-ADUser -LDAPFilter ... doesn't throw an exception when no users are found, so the fact that is says the username was found tells you nothing - it would have told you that whether it found 0 or 100 :)

    Explicitly test whether it actually returns anything to make it work:

    ForEach($User in $List){
        Write-host "Now checking $User"
    
        Try {
            # search for matching users
            $matchingUsers = Get-ADUser -LDAPFilter "(anr=$User)" -Properties * |
                Select-object DisplayName,UserPrincipalName,mail,Enabled
    
            if(-not $matchingUsers){
                # no users found? throw to enter the catch block
                throw
            }
            # otherwise proceed to export to CSV
            $matching |Export-CSV -Append $OutputFileResults -NoTypeInformation
            Write-host "$User found successfully" -foregroundcolor Green
        }
        Catch {
            $User | Export-CSV -Append $OutputFileFailed -NoTypeInformation
            Write-host "$User not found" -foregroundcolor Red
        }
    }