1

我有一个包含特殊字符的 EN/FR 用户列表。我正在尝试获取他们的 SamAccountName,但脚本无法正常工作:

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear();
cls
$ErrorActionPreference = "STOP"
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname,Surname -Delimiter ","
$CompleteReport=@()
ForEach ($Name in $Names)
{
    $FirstFilter = $Name.Givenname
    $SecondFilter = $Name.Surname
    Write-Host $Name.Givenname, $Name.Surname
    $aduser = Get-ADUser -Filter { GivenName -like $FirstFilter -and Surname -like $SecondFilter}  | select enabled, GivenName,  Surname, samaccountname, UserPrincipalName
    $CompleteReport = $CompleteReport+$aduser
} 
$CompleteReport | Export-Csv 'C:\output.csv' -NoTypeInformation

问题是我的输入列表不清楚,这导致循环继续进行而没有向我显示导致问题的项目的错误。如何捕获导致此错误的用户名?

4

1 回答 1

0

错误可能来自CSV 中GivenNameSurname上的空字符串,至于对该问题进行排序,无法修复 CSV 本身,仅通过GivenNameSurname搜索 AD 用户不会带来准确的结果。以下内容至少应处理 CSV 中丢失的数据,并指出那些无法找到的用户,以便您修复 CSV。

$ErrorActionPreference = "STOP"
# -Delimiter ',' is already assumed
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname, Surname 

$result = forEach($name in $names) {
    $givenname = if($name.GivenName) {
        '(givenName={0})' -f $name.Givenname
    }
    $surname = if($name.Surname) {
        '(surname={0})' -f $name.Surname
    }
    $aduser = Get-ADUser -LDAPFilter "(&${surname}${givenname})"
    if(-not $aduser) {
        Write-Warning "Can't find Name: $($name.Givenname) and Surname: $($name.Surname)"
        continue
    }
    $aduser
}

$result | Select-Object Enabled, GivenName, Surname, SamAccountName, UserPrincipalName |
Export-Csv 'C:\output.csv' -NoTypeInformation
于 2022-02-12T04:51:12.387 回答