I'm trying to get a list of AD user's logon names from a list of display names using this script.
Import-Csv 'C:\temp\displaynames.csv'
ForEach-Object {
$name = $_.displayname
Get-ADUser -Filter * -Properties DisplayName | Where-Object {$_.displayname -eq $name}
} |
Select-Object SamAccountName, DisplayName |
Export-Csv 'C:\Temp\Results.csv' -NoType
The script appears to run without errors but I only get results for display names without spaces in them. Could it be that I need to specify more information such as the domain name? Flailing that could this be down to the formatting of my displaynames.csv list?
So far I have tried:
All with the same result.
You could do the following LDAPFilter trick to query all users at once, this should be as efficient as it gets when querying multiple Active Directory users (with the AD Module; [adsi]
should be even better) it does not look pretty though. I have also added a Trim
for each element of your CSV, to remove any leading or trailing space which could be what's causing the issue.
# Trim any trailing and leading spaces for each element
$users = (Import-Csv 'C:\temp\displaynames.csv').displayname.ForEach('Trim')
$filter = '(|(displayname={0}))' -f ($users -join ')(displayname=')
# - Something like:
# $users = 'Joe Bloggs', 'John Doe', 'David Gilmour'
# - Becomes:
# (|(displayname=Joe Bloggs)(displayname=John Doe)(displayname=David Gilmour))
Get-ADuser -LDAPFilter $filter -Properties DisplayName |
Select-Object samAccountName, DisplayName |
Export-Csv 'C:\Temp\Results.csv' -NoTypeInformation