PowerShell脚本修改:让重复邮箱均添加location_id后缀
PowerShell脚本修改:让所有重复邮箱统一添加location_id后缀
问题场景
从CSV文件读取数据,其中name列内容如下:
shouston cgonzalez bbrown hlader kpesavento jbloom polson bcharlow bcharlow bkalt
需求为生成邮箱时,所有重复的邮箱前缀对应的行(包括第一次出现的)都要添加location_id后缀,例如重复的bcharlow需生成bcharlow1@abc.com、bcharlow2@abc.com,而非原脚本产出的bcharlow@abc.com、bcharlow2@abc.com。
原脚本如下:
# Grab CSV file $inputFile = Import-Csv -Path $filePath $text = (Get-Culture).TextInfo $HashSet = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($line in $inputFile) { $name = $line.name $line.name = $text.ToTitleCase($name) $firstName = $line.name.split(" ")[0] $lastName = $line.name.split(" ")[1] $newEmail = ($firstName[0] + $lastName).toLower() if (!$HashSet.Add($newEmail)) { $line.email = ($firstName[0] + $lastName + $line.location_id + "@abc.com").toLower() } else { $line.email = ($firstName[0] + $lastName + "@abc.com").toLower() } } $inputFile | Export-Csv $fullPath
修改后的脚本
# 读取CSV文件 $inputFile = Import-Csv -Path $filePath $text = (Get-Culture).TextInfo # 第一步:统计每个邮箱前缀的出现次数,识别重复前缀 $emailPrefixCount = [System.Collections.Generic.Dictionary[string, int]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($line in $inputFile) { $formattedName = $text.ToTitleCase($line.name) $firstName = $formattedName.Split(" ")[0] $lastName = $formattedName.Split(" ")[1] $emailPrefix = ($firstName[0] + $lastName).ToLower() if ($emailPrefixCount.ContainsKey($emailPrefix)) { $emailPrefixCount[$emailPrefix]++ } else { $emailPrefixCount[$emailPrefix] = 1 } } # 第二步:遍历生成邮箱,重复前缀的所有行统一添加location_id foreach ($line in $inputFile) { $line.name = $text.ToTitleCase($line.name) $firstName = $line.name.Split(" ")[0] $lastName = $line.name.Split(" ")[1] $emailPrefix = ($firstName[0] + $lastName).ToLower() if ($emailPrefixCount[$emailPrefix] -gt 1) { $line.email = ($emailPrefix + $line.location_id + "@abc.com").ToLower() } else { $line.email = ($emailPrefix + "@abc.com").ToLower() } } # 导出修改后的CSV,避免生成类型信息 $inputFile | Export-Csv -Path $fullPath -NoTypeInformation
核心修改说明
- 新增前缀统计步骤:先遍历一次所有行,用字典记录每个邮箱前缀的出现次数,以此准确判断哪些前缀是重复的(出现次数>1)
- 调整邮箱生成逻辑:第二次遍历行时,只要前缀属于重复范畴,无论首次还是后续出现,都添加
location_id后缀;非重复前缀保持原格式 - 优化导出参数:添加
-NoTypeInformation参数,避免Export-Csv生成不必要的类型注释行
内容的提问来源于stack exchange,提问作者Art
相关产品推荐
相关产品推荐

