You need to enable JavaScript to run this app. 如何使用PowerShell从samaccountname列表提取DisplayName并输出指定格式
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell从samaccountname列表提取DisplayName并输出指定格式

自定义拼接格式输出的PowerShell实现

原脚本的输出逻辑是导出标准CSV,和目标格式不匹配,直接调整拼接和输出逻辑即可实现需求。

适配目标的脚本

简化版(适配账号全部存在、无空值的场景)

Import-Module ActiveDirectory

$finalResult = Get-Content 'C:\Temp\Users.txt' | ForEach-Object {
    $adUser = Get-ADUser $_ -Properties DisplayName
    # 单条记录按「账号(显示名)」格式拼接
    "$($adUser.SamAccountName)($($adUser.DisplayName))"
} -join ';'

# 控制台输出结果
$finalResult
# 结果写入文本文件
$finalResult | Set-Content -Path 'C:\Temp\result.txt' -NoNewline

鲁棒增强版(处理无效账号、空行等异常场景)

Import-Module ActiveDirectory

$finalResult = Get-Content 'C:\Temp\Users.txt' | 
    Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | # 跳过文本中的空行
    ForEach-Object {
        $samName = $_.Trim()
        $adUser = Get-ADUser $samName -Properties DisplayName -ErrorAction SilentlyContinue
        if ($adUser) {
            "$($adUser.SamAccountName)($($adUser.DisplayName))"
        } else {
            # 无效账号输出提示,方便后续排查
            "$samName(未匹配到AD用户)"
        }
    } | 
    Where-Object { $_ } -join ';'

$finalResult | Set-Content -Path 'C:\Temp\result.txt' -NoNewline

效果说明

脚本运行后最终生成的单行文本完全匹配你期望的格式:

user01(John T);user02(Sandra M)

适配提示:PowerShell 5.1及更早版本可直接使用上述脚本,PowerShell 7+版本也可将-join ';'替换为原生命令Join-String -Separator ';',效果一致。


内容的提问来源于stack exchange,提问作者Arbelac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 23:15:04