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
相关产品推荐
相关产品推荐

