2014-09-04 50 views
0

我有一個csv文件,我想將文件中的電子郵件地址與AD中的正確電子郵件地址進行比較, t匹配我想更正郵件地址,然後將其全部寫入新文件。Powershell - 從csv中讀取並更改對象中的值然後寫入新的csv文件

內容someFile.csv的腳本

user_id name   username email    password admin 
1  Mr Foo   mrFoo1  [email protected] a   0 
2  Ms Bar   msBar2  [email protected] 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 ";" 
+0

問題是什麼? – 2014-09-04 08:09:48

+0

當使用替換錯誤的電子郵件地址時,它不會按我的意願工作。而不是 user_id : 13 name : Ingrid Name username : ajaxoi01 email : [email protected] password : a admin : 0 我得到 @{user_id=14; name=Thomas SomeName; username=akesst01; [email protected]; password=a; admin=0} 然後我的意思是格式,而不是內容。它不再承認它作爲一個對象。 – 2014-09-04 08:50:44

+0

正如您所呈現的那樣someFile.csv不是一個CSV文件,而是一個位置字段格式。 – JPBlanc 2014-09-04 14:01:35

回答

0

我想你可以通過改變線達到所需的輸出:

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

到:

$a.email = $realMail.EmailAddress