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:
- A list with the names on each row (no double quotes or quotes)
- each name encapsulated by ' ' (i.e. 'Joe Bloggs')
- Each name encapsulated by " " (i.e. "Joe Bloggs")
All with the same result.
CodePudding user response:
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
CodePudding user response:
I always use Excel to edit and save CSV files because it will always create a standard valid CSV file, and it will handle all the quoting. The CSV should look like:
C:\temp\displaynames.csv
DisplayName
"Joe Bloggs"
"James Smith"
The script that you have right now is very inefficient. Each user you loop through, you get all users, then use the Where-Object to find what you are looking for. It is much much easier to simply use the Get-ADUser -Filter command to do all the work for you:
$CSV = Import-Csv 'C:\temp\displaynames.csv'
$CSV | ForEach-Object {
$name = $_.displayname
Get-ADUser -Filter {DisplayName -like $name} -Properties DisplayName
} |
Select-Object SamAccountName, DisplayName |
Export-Csv 'C:\Temp\Results.csv' -NoType
