首页 > 解决方案 > 更改 CSV 中的电子邮件地址

问题描述

我正在编写 PowerShell 代码以将电子邮件地址导出到 csv 文件并进行编辑。我写了以下内容:

# Script to get all DLs and email addresses in csv file
Get-ADGroup -Filter 'groupcategory -eq "distribution"' -Properties * |
    select Name, mail |
    Export-csv "C:\temp\Distribution-Group-Members.csv"

# Following will import the csv, make new column as proxy and save the file
# as update.csv 
Import-Csv "C:\temp\Distribution-Group-Members.csv" |
    Select-Object "Name", "mail", @{n = "proxy"; e = "mail"} |
    Export-Csv "c:\temp\Distribution-Group-Members-Updated.csv" -NoTypeInfo

# Following script can import the csv and set proxy addresses from proxy
# column 
Import-Csv "c:\temp\Distribution-Group-Members-Updated.csv" |
    Foreach {
        Get-ADGroup $_.Name | Set-ADGroup -Add @{
            proxyaddresses = ($_.proxy -split ";")
        }
   }

现在,我想在脚本中添加另外 2 个功能:

因此,假设我的 DL 名称是“DL Test”,电子邮件是“test@abc.com”=> 脚本应该将 DL 的电子邮件地址更新为“test@xyz.com”,并将“smtp:test@abc.com”添加为代理邮件地址

有人可以建议,我怎样才能做到这一点?

标签: powershellactive-directoryexport-to-csv

解决方案


你写的部分:

select-object "Name", "mail", @{n = "proxy"; e = "mail"}| 

proxy部分称为计算属性。前两个只有名称NameMail直接从输入对象复制,但使用@{..}语法,您可以使用代码来计算新值。

因此,您可以使用它来实现您想要的更改:

Import-Csv -Path 'C:\temp\Distribution-Group-Members.csv' | 

  Select-Object -Property Name, 
   @{Label='Mail';  Expression={$_.Mail -replace 'abc', 'xyz'}}, 
   @{Label='Proxy'; Expression={"SMTP:$($_.Mail -replace 'abc', 'xyz');smtp:$($_.Mail)"}}|

  Export-csv 'C:\temp\Distribution-Group-Members.csv' -NoTypeInformation

推荐阅读