基于 CSV 文件中的电子邮件设置 ADUser

Set-ADUser based on Email in CSV File

我正在尝试从 csv 文件中读取信息,如果在 csv 文件中找到电子邮件地址,则使用它向我们的活动目录添加 phone 号码。 (我知道 EmailAddress 属性是不可靠的,但我必须根据导出数据的位置来使用它)。我有一个 powershell 脚本:

Import-Module ActiveDirectory
$csv = Import-Csv c:\users\user1\Desktop\userphones2.csv
foreach ($line in $csv) {
    Get-ADUser -Filter {EmailAddress -eq $line.email} | 
    Set-ADUser -OfficePhone $line.phone
}

当我 运行 这样做时,对于数据文件中的每条记录,我都会收到

错误

Get-ADUser : Property 'email' not found in object of type: 'System.Management.Automation.PSCustomObject'

CSV 文件的结构如下:

#TYPE System.Data.DataRow
"email","phone"
"user@example.com","8885555555"
"user2@example.com","8885555552"

如果我在 foreach 循环中执行 Write-Output 而不是尝试获取数据,这会起作用。我发现了许多不同的语法,描述了如何为这些过滤器将变量放在这样的行中,但没有任何效果。我如何让这个过滤器工作?

您在 AD 中为电子邮件 属性 使用了错误的名称。是 mail 而不是 EmailAddress。我在 PowerShell 中对此进行了测试,它对我有用。

此外,您不能在 PowerShell 不知道如何处理的过滤器中使用 $line.email。我不知道这样做的技术原因,但我从来没有让它那样工作,所以我总是把它放在一个变量中。试试这个:

Import-Module ActiveDirectory
$csv = Import-Csv c:\users\user\Desktop\userphones2.csv
foreach ($line in $csv) {
    $email = $line.email
    Get-ADUser -Filter {mail -eq $email} | 
        Set-ADUser -OfficePhone $line.phone
}