如何修改PowerShell代码消除导出CSV空白行并显示Not Found
问题解决:PowerShell查询AD用户导出CSV去除空白行并标记未找到条目
问题分析
原代码的核心问题在于:无论AD中是否匹配到用户,都会先输出一个基于查询结果$u的自定义对象——当未找到用户时,$u为空,这个对象的所有属性都是空值,随后又输出一条标记为Not Found的对象,导致CSV中出现空白行(空属性对象行)和有效标记行并存的情况。同时全局设置ErrorActionPreference = 'Stop'会让Get-ADUser未找到用户时直接抛出终止错误,中断整个循环。
修改后的代码
# 加载窗体程序集 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $notfound = 'Not Found' # 选择待处理的CSV文件 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.Title = "请选择要处理的CSV文件" $OpenFileDialog.InitialDirectory = $InitialDirectory $OpenFileDialog.Filter = "CSV (*.csv) | *.csv" $OpenFileDialog.ShowDialog() | Out-Null $Path = $OpenFileDialog.Filename $userList = Import-Csv -Path $Path # 选择保存路径 Function Get-FileName($initialDirectory) { [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog $SaveFileDialog.Title = "请选择文件保存路径" $SaveFileDialog.initialDirectory = $initialDirectory $SaveFileDialog.filter = "CSV file (*.csv)|*.csv|所有文件(*.*)|*.*" $SaveFileDialog.ShowDialog() | Out-Null $SaveFileDialog.filename } $SaveMyFile = Get-Filename # 遍历处理每个邮箱条目 $userList | ForEach-Object { $targetEmail = $_.email try { # 查询AD用户,未找到时抛出指定错误 $u = Get-ADUser -Filter "EmailAddress -eq '$targetEmail'" -Properties mail, samaccountname, manager -ErrorAction Stop # 处理经理信息,无经理时标记为未找到 $managerName = if ($u.Manager) { (Get-ADUser $u.Manager).Name } else { $notfound } $managerEmail = if ($u.Manager) { (Get-ADUser -Property emailaddress $u.Manager).emailaddress } else { $notfound } # 输出匹配到的用户信息 [PSCustomObject]@{ email = $u.mail samaccountname = $u.samaccountname Manager = $managerName ManagerEmail = $managerEmail } } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { # 未找到用户时输出标记信息,保留原邮箱方便核对 [PSCustomObject]@{ email = $targetEmail samaccountname = $notfound Manager = $notfound ManagerEmail = $notfound } } } | Export-CSV -Path $SaveMyFile -NoTypeInformation -Encoding UTF8
关键修改点
- 精准错误捕获:移除全局
ErrorActionPreference = 'Stop',仅在Get-ADUser中指定-ErrorAction Stop,并捕获ADIdentityNotFoundException,只处理未找到用户的情况,避免循环中断。 - 逻辑重构:通过
try/catch分支分别输出“匹配到的用户信息”或“未找到标记信息”,确保每行都是有效条目,彻底消除空白行。 - 保留原邮箱:未找到用户时保留输入的原邮箱地址,方便后续核对,而非直接替换为
Not Found。 - 兼容无经理场景:如果用户没有配置经理属性,对应字段也标记为
Not Found,避免出现空值。 - 编码优化:导出CSV时添加
-Encoding UTF8,避免中文乱码问题。
内容的提问来源于stack exchange,提问作者Chris Newton
相关产品推荐
相关产品推荐

