简体   繁体   中英

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

I am trying to take a CSV, with a list of emails, and use those emails to lookup the user in AD, and the find the whenCreated attribute, and add that to a column in that CSV.

Currently, I am using the following line to do the lookup:


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

Ideally, this should instantiate a variable named $created , then assign the date created to that variable, of whatever email is passed. This line works alone, and work with individual lookups. However, when I add that line into a foreach loop, the $created variable is empty. It builds the new CSV just fine but the column I want to change ( custom ) remains unpopulated.

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"

As its own line, it works fine with the variable $email , or anything else, but in the foreach loops, the $created variable is always empty. The same is true of any other attribute, such as SamAccountName, Displayname, etc.

Any ideas?

I guess you want something like this:

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 maps whenCreated to a property called Created , which is the whenCreated LDAP attribute converted to local DateTime object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM