Reputation: 59
I have a list of displaynames and I need to get their AD informations.
Get-Content "C:\displaynames.txt" |
foreach {
$givenname,$surname = $_ -split ' '
if (Get-ADUser -Filter "surname -eq '$surname' -and givenname -eq '$givenname'"){
Get-ADUser -Filter { displayName -match $_} -Properties EmailAddress, Manager | Select Givenname, Surname, SamAccountName, EmailAddress, Manager}
else {Get-ADUser -Filter { displayName -like "AD Test"} -Properties EmailAddress, Manager | Select Givenname, Surname, SamAccountName, EmailAddress, Manager}
} | Export-Csv -Path C:\result.csv
This works fine, but only if users have no middle names ex. John Moore If the user has a middle name, it doesn't pick it up. How can I change the script so it picks up users with middle names ex. John Roger Moore?
Upvotes: 1
Views: 3440
Reputation: 61013
As Mathias R. Jessen already commented, you can use the -Filter
on property DisplayName directly.
The Filter should be a string, not a scriptblock.
Using -Filter
also has the advantage that you can suppress exceptions being thrown, so I would build in a step to confirm that we indeed did find a user with that displayname:
Get-Content "C:\displaynames.txt" | ForEach-Object {
$user = Get-ADUSer -Filter "DisplayName -eq '$_'" -Properties DisplayName, EmailAddress, Manager -ErrorAction SilentlyContinue
if ($user) {
# output the wanted properties as **object**
$user | Select-Object Givenname, Surname, SamAccountName, EmailAddress, Manager
}
else {
# nobody in this domain with a displayname like that..
Write-Warning "User '$_' could not be found.."
}
} | Export-Csv -Path 'C:\result.csv' -NoTypeInformation
Note that the Manager
property is in the form of the managers DistinguishedName. If you want to get other properties for the manager, like his/her name, you will have to use Get-ADUser -Identity $user.Manager
to get the wanted property there too
Upvotes: 1
Reputation:
The basic question here is how to account for middle names.
PowerShell 5 has some AI-powered cmdlets.
Here, I will quote an example from the documentation.
Example 2: Simplify format of a string
$composers = @("Johann Sebastian Bach", "Wolfgang Amadeus Mozart", "Frederic Francois Chopin", "Johannes Brahms") $composers | Convert-String -Example "first middle last=last, first" Bach, Johann Mozart, Wolfgang Chopin, Frederic Brahms, Johannes
The first command creates an array that contains first, middle and last names. Note that the last entry has no middle name.
The second command formats the names according to the example. It puts the last name first in the output, followed by the first name. All middle names removed; entry without middle name is handled correctly.
Upvotes: 0