You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell读取CSV单列并替换为AzureAD用户显示名

PowerShell 邮箱转AzureAD显示名解决方案

修正后的Convert-UserColumn函数代码

function Convert-UserColumn {
    param(
        [Parameter(Mandatory=$true)]
        [string]$CurDate
    )
    $ImportPath = "C:\AuditLogSearch\$($CurDate) Final Audit-Log-Records.csv"
    $ExportPath = "C:\AuditLogSearch\FinalFile.csv"

    # 导入源CSV文件
    $sourceRecords = Import-Csv -Path $ImportPath -Encoding UTF8

    # 初始化邮箱-显示名缓存,避免重复查询AzureAD提升效率
    $mailDisplayNameMap = @{}

    # 遍历所有记录处理User列
    $outputRecords = foreach ($record in $sourceRecords) {
        $currentMail = $record.User.Trim()
        # 先查缓存,已查询过的直接取结果
        if (-not $mailDisplayNameMap.ContainsKey($currentMail)) {
            # 从AzureAD查询对应用户的显示名,查不到的保留原邮箱避免空值
            $azureUser = Get-AzureADUser -Filter "Mail eq '$currentMail'" -ErrorAction SilentlyContinue
            $displayName = if ($azureUser) { $azureUser.DisplayName } else { $currentMail }
            $mailDisplayNameMap[$currentMail] = $displayName
        }
        # 替换User列内容,保留其余列不变
        $record.User = $mailDisplayNameMap[$currentMail]
        $record
    }

    # 导出结果到目标CSV
    $outputRecords | Export-Csv -Path $ExportPath -Encoding UTF8 -NoTypeInformation
}

逻辑说明

  • 新增$CurDate作为必填入参,避免变量作用域问题导致路径识别失败
  • 先调用Import-Csv加载源文件为结构化对象,才能正确读取每一行的User、Date&Time、Activity字段
  • 新增邮箱和显示名的映射缓存,同一个邮箱仅需查询一次AzureAD,大幅降低接口请求次数、提升运行效率
  • 查询AzureAD用户时使用Filter参数按邮箱过滤,查询失败的场景保留原邮箱作为兜底,避免字段为空
  • 处理后的记录直接保留原有的Date&Time、Activity字段,仅替换User列内容,完全符合输出要求

调用注意事项

  • 调用Convert-UserColumn前必须先执行Connect-AzureActiveDirectory完成AzureAD连接
  • 调用时需要传入当前日期参数,示例:Convert-UserColumn -CurDate "20240520"
  • 如果你使用自定义的Get-AzureDisplayName函数查询显示名,把代码中Get-AzureADUser相关的查询逻辑替换为你的自定义函数调用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:45:11