Powershell - 从csv读取并更改对象中的值,然后写入新的csv文件

时间:2014-09-04 07:54:26

标签: powershell

我有一个csv文件,我想要将文件中的电子邮件地址与AD中的正确电子邮件地址进行比较,如果它们不匹配我想要更正邮件地址然后将其全部写入新文件。

someFile.csv的内容

user_id name            username    email               password    admin
1       Mr Foo          mrFoo1      mrFoo1@domain.com   a           0
2       Ms Bar          msBar2      msBar2@domain.com   a           1

剧本内容

$current = Import-Csv c:\someFile.csv -Delimiter ";"
$new = @()

foreach($a in $current){
    try {
        if (Get-ADUser $a.username -Properties EmailAddress | where {$_.EmailAddress -eq $null }) {
            <set the field email to N/A>
                    }
        else {
            $realMail =  Get-ADUser $a.username -Properties EmailAddress  | select EmailAddress
            if ($a.email = ($a.username + "@domain.com")) { 
                $a = $a -replace $a.email, $realMail.EmailAddress #does not work
            }
        }
        $new += $a
        }
    catch [exception]{
        $_.Exception.message
    }
}
$new | Select-Object user_id, name, username, email, password, admin | Export-Csv -Path c:\someNewFile.csv -Encoding UTF8 -NoTypeInformation -Delimiter ";"

1 个答案:

答案 0 :(得分:0)

我认为您可以通过更改行来实现所需的输出:

$a = $a -replace $a.email, $realMail.EmailAddress #does not work

为:

$a.email = $realMail.EmailAddress