用 DisplayName 查找 AD 用户信息

Find AD user information with DisplayName

我有一个显示名称列表,我需要获取他们的广告信息。

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

这很好用,但前提是用户没有中间名,例如。约翰摩尔 如果用户有中间名,它不会选择它。 我怎样才能更改脚本,以便它选择具有中间名 ex 的用户。约翰·罗杰·摩尔?

这里的基本问题是如何计算中间名。

PowerShell 5 有一些 AI 驱动的 cmdlet。

在这里,我将引用文档中的示例。

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.

正如 Mathias R. Jessen 已经评论的那样,您可以直接在 属性 DisplayName 上使用 -Filter
过滤器应该是 字符串 ,而不是脚本块。

使用 -Filter 的另一个优点是可以抑制抛出异常,因此我会构建一个步骤来确认我们确实找到了具有该显示名称的用户:

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

请注意,Manager 属性 的形式是经理 DistinguishedName。如果你想获得经理的其他属性,比如 his/her 名字,你将不得不使用 Get-ADUser -Identity $user.Manager 来获得想要的 属性