PowerShell如何将SharePoint格式字符串转换为标准邮箱地址?
方法1:拆分数组处理(兼容多部分姓名)
这种方式适合姓名部分包含多个下划线的场景(比如john_michael_smith_domain_com转成john.Michael.Smith@domain.com):
- 定义输入字符串并拆分为数组
$spString = "john_smith_domain_com" $parts = $spString -split "_"
- 分离姓名与域名部分
# 姓名部分:除最后两个元素外的所有内容 $nameSegments = $parts[0..($parts.Count - 3)] # 域名部分:最后两个元素(主域+后缀) $domainSegments = $parts[-2..-1]
- 格式化姓名(首字母小写,后续姓名段首字母大写)
$formattedName = $nameSegments | ForEach-Object { if ($_ -eq $nameSegments[0]) { $_ } else { (Get-Culture).TextInfo.ToTitleCase($_) } } -join "."
- 格式化域名并拼接邮箱
$formattedDomain = $domainSegments -join "." $emailAddress = "$formattedName@$formattedDomain" # 输出结果:john.Smith@domain.com
方法2:正则表达式替换(简洁写法)
如果姓名固定为两段(名+姓),可以用正则一次性替换:
$spString = "john_smith_domain_com" $emailAddress = $spString -replace '^(\w+)_(\w+)_(\w+)_(\w+)$', '$1.$2@$3.$4' -replace '(\.\w+)', { $args[0].Value.Substring(0,1) + $args[0].Value.Substring(1).ToUpper() } # 输出结果:john.Smith@domain.com
如果姓名可能有多段,正则可以调整为更通用的写法:
$spString = "john_michael_smith_domain_com" $emailAddress = $spString -replace '^(.*)_(\w+)_(\w+)$', { $namePart = $args[0].Groups[1].Value -replace '_', '.' -replace '(\.\w+)', { $args[0].Value.Substring(0,1) + $args[0].Value.Substring(1).ToUpper() } "$namePart@$($args[0].Groups[2].Value).$($args[0].Groups[3].Value)" } # 输出结果:john.Michael.Smith@domain.com
内容的提问来源于stack exchange,提问作者Josh B
相关产品推荐
相关产品推荐

