我是Powershell的新手,但我已经尽力了。有一个.csv文件,小示例:
id,location_id,name,title,email,directorate
1,1, Amy lee,Singer,,
2,2,brad Pitt,Actor,,Production
3,5,Steven Spielberg,Producer,spielberg@my.com,Production
需要:
- 将名字和姓氏改为大写,例如Brad Pitt、Amy Lee
- 创建电子邮件,其模式为名字+姓氏的第一个字母,小写字母为@google.com,值为location_id,例如-alee1@google.com,bpitt2@google.com
- 将其保存到具有相同结构的新file.csv中,例如:
id,location_id,name,title,email,directorate
1,1, Amy Lee,Singer,alee1@google.com,
2,2,Brad Pitt,Actor,bpitt@google.com,Production
3,5,Steven Spielberg,Producer,sspielberg@google.com,Production
我写了一个脚本,它的命令一个接一个地执行任务,但不知道如何保存它——没有新的.csv文件:
param (
[string] $file_path
)
$inputFile = Import-Csv -Path $file_path
foreach ($line in $inputFile) {
$line.name = (Get-Culture).TextInfo.ToTitleCase($line.name)
$firstName = $line.name.split(" ")[0]
$lastName = $line.name.split(" ")[1]
$newEmail = ($firstName[0] + $lastName + $line.location_id + "@google.com").toLower()
}
也许,还有更清洁的解决方案?
您的代码即将完成,但这里有一种更简单的方法。您已经在使用TextInfo.ToTitleCase
,但对于电子邮件地址,您可以使用-replace
运算符和一点正则表达式来简化它。
您可以在以下链接中找到有关regex模式的信息:https://regex101.com/r/WKF9R5/1
$txtInfo = [cultureinfo]::InvariantCulture.TextInfo
$csv = Import-Csv pathtocsv.csv
foreach($line in $csv) {
$name = $line.name
$line.name = $txtInfo.ToTitleCase($name)
# Example: 'brad Pitt' => bPitt
$line.email = ($name -replace '(?<=^w{1})w+s').ToLower() + $line.location_id + '@google.com'
}
$csv | Export-Csv pathtonewcsv.csv -NoTypeInformation
使用问题中的Csv的最终输出:
id location_id name title email directorate
-- ----------- ---- ----- ----- -----------
1 1 Amy Lee Singer alee1@google.com
2 2 Brad Pitt Actor bpitt2@google.com Production
3 5 Steven Spielberg Producer sspielberg5@google.com Production