我可以单独获取 AD 帐户属性,但不能在 foreach 循环中获取?

I can get AD account attributes individually, but not in the foreach loop?

我正在尝试获取包含电子邮件列表的 CSV,并使用这些电子邮件在 AD 中查找用户,然后找到 whenCreated 属性,并将其添加到该 CSV 中的列.

目前,我正在使用以下行进行查找:


    $created = Get-ADUser -filter "EmailAddress -eq '$email'" -property whenCreated | select -ExpandProperty whenCreated 

理想情况下,这应该实例化一个名为 $created 的变量,然后将创建日期分配给该变量,无论传递的是什么电子邮件。这条线单独工作,并与单独的查找一起工作。但是,当我将该行添加到 foreach 循环中时,$created 变量为空。它可以很好地构建新的 CSV,但我要更改的列 (custom) 仍未填充。

Import-Module ActiveDirectory
[array]$CSVfile = Import-CSV "C:\Users\blahblahblah\temp\to_upload.csv" -Header "first_name", "last_name", "email", "group", "title", "department", "phone", "address1", "address2", "city", "state", "zip", "country", "custom", "manager_name", "manager_email", "start_date" 
for($i=0; $i -ne $CSVfile.count; $i++) {
    $email = $CSVfile[$i]."email"
    write-host $email
    $created = Get-ADUser -filter "EmailAddress -eq '$email'" -property whenCreated | select -ExpandProperty whenCreated
    Write-Host($CSVfile[$i].Email + ", " + $created) -NoNewline
    Write-Host ""
    $CSVfile[$i].custom= $created
}

$CSVfile | Export-CSV "C:\Users\blahblahblah\temp\to_upload_1.csv"

作为它自己的一行,它与变量 $email 或其他任何东西一起工作正常,但在 foreach 循环中,$created 变量始终为空。任何其他属性也是如此,例如 SamAccountName、Displayname 等。

有什么想法吗?

我猜你想要这样的东西:

Import-Module ActiveDirectory

$headers = "first_name", "last_name", "email", "group", "title", "department", "phone", 
           "address1", "address2", "city", "state", "zip", "country", "custom", 
           "manager_name", "manager_email", "start_date" 

$CSVfile = Import-CSV -Path "C:\Users\blahblahblah\temp\to_upload.csv" -Header $headers
$newData = foreach ($item in $CSVfile) {
    $item.custom = (Get-ADUser -Filter "EmailAddress -eq '$($item.email)'" -Properties Created -ErrorAction SilentlyContinue).Created
    # output the updated item
    $item
}

$newData | Export-CSV "C:\Users\blahblahblah\temp\to_upload_1.csv" -NoTypeInformation

PowerShell 将 whenCreated 映射到名为 Created 的 属性,这是转换为本地 DateTime 对象的 whenCreated LDAP 属性