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

PowerShell处理CSV格式转换:提取AAD用户UPN并格式化输出

问题分析与解决方案

原脚本输出格式错误的核心原因:使用Set-Content直接输出$userlist时,PowerShell会将每个PSCustomObject转换为默认的字符串表示(即@{UserPrincipalName=xxx}),不符合需求格式。

修改后的完整脚本

Write-Host "Fetching data from Azure Active Directory..."
$cred = New-Object -TypeName PSCredential -argumentlist $username, $pwd
# Connect to M365
Connect-MsolService -Credential $cred
$Users = Get-MsolUser -All | Where-Object { $_.UserType -ne "Guest" }

# 直接提取所有非访客用户的UserPrincipalName属性
$userPrincipals = $Users.UserPrincipalName

# 格式化为单引号包裹、逗号分隔的字符串(PowerShell 5.1+支持Join-String)
$formattedOutput = $userPrincipals | ForEach-Object { "'$_'" } | Join-String -Separator ', '

$Output = "c:\logging\data\AAD_Users_only.csv"
Set-Content -Path $Output -Value $formattedOutput

兼容旧版PowerShell的写法

如果你的PowerShell版本低于5.1(不支持Join-String),可将格式化部分替换为:

$formattedOutput = ($userPrincipals | ForEach-Object { "'$_'" }) -join ', '

修复已生成的错误格式文件

若已有错误格式的输出文件,可通过以下脚本修复:

$inputPath = "c:\logging\data\AAD_Users_only.csv"
$outputPath = "c:\logging\data\AAD_Users_fixed.csv"

$fixedContent = Get-Content $inputPath | ForEach-Object {
    # 匹配每行中UserPrincipalName=后的内容
    if ($_ -match 'UserPrincipalName=(.+)') {
        "'$($matches[1])'"
    }
} | Join-String -Separator ', '

Set-Content -Path $outputPath -Value $fixedContent

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:32:19