如何在foreach循环中使用Powershell写入CSV中的一个条目

问题描述

我正在尝试编写一个脚本,该脚本将采用现有的 CSV 文件,其中“部门”为空列,对于每一行,使用该行中存在的电子邮件地址对该用户的电子邮件地址进行反向查找部门,然后将该部门值写入“部门”列中的行。

目前,我可以读取 CSV、获取电子邮件获取部门,但我不知道如何将该行的“Department”值更改为 $department 变量中存储的值。

Import-Module ActiveDirectory

$CSVfile = Import-CSV "C:\Users\abcdefg\temp\fieldstaffreport.csv" -Header "training","fname","lname","email","department","group","completion","url","date1","date2"


$CSVfile = foreach ($i in $CSVfile) {
    $email = $i.Email
    $department = Get-ADUser -filter "EmailAddress -eq '$email'" -property department | select -expandproperty department
    Write-Host($i.Email + "," + $department) -NoNewline
    $i.department= $department
}

$CSVfile | Export-CSV "C:\Users\abcdefg\temp\output.csv"

我相信第 10 行(我写 $i.department = $department 的地方)应该更改该值。此脚本使用 foreach 循环循环遍历 CSV 中的每一行。

谁能告诉我我做错了什么。我已经用尽了所有与此相关的指南和文章,但我不明白为什么这不起作用。

write-host 输出完美运行,显示电子邮件地址,然后是 AD 中的部门值,以逗号分隔。这一切都与实际用户数据和所有内容正确对齐。

谢谢

解决方法

你能检查一下吗?

[array]$CSVfile = Import-CSV "C:\Users\abcdefg\temp\fieldstaffreport.csv" -Header "training","fname","lname","email","department","group","completion","url","date1","date2"


for($i=0; $i -ne $CSVfile.count; $i++) {
    $email = $CSVfile[$i].Email
    $department = Get-ADUser -filter "EmailAddress -eq '$email'" -property department | select -expandproperty department
    Write-Host($CSVfile[$i].Email + "," + $department) -NoNewline
    $CSVfile[$i].department= $department
}

$CSVfile | Export-CSV "C:\Users\abcdefg\temp\output.csv"