PowerShell脚本检测AD组用户配置文件导出CSV异常求助
问题根因
原脚本Profile_Search字段仅返回单个用户结果的核心原因有3个:
- 循环遍历AD组成员时,每次都直接给
$profileexists变量赋值,没有做结果累加,循环结束后变量只会保留最后一个用户的检测状态,前面所有用户的结果都被覆盖 - 对单个字符串错误使用
-join操作符:-join的作用是拼接数组的多个元素,对单个字符串使用该操作符不会产生任何拼接效果 - 额外性能问题:原脚本把AD组成员查询放在了每台计算机的循环内部,有多少台服务器就会重复查多少次AD,执行效率极低
修复后完整脚本
Clear-History $ErrorActionPreference= 'silentlycontinue' # 提前一次性获取AD目标组成员,避免重复查询AD $targetUsers = Get-ADGroupMember -Identity TestDisabledUsers | Select-Object -ExpandProperty SamAccountName $outputFolderName = 'ProfileAudit ' + $(Get-Date -f dd-MM-yyyy) $outputpath = "C:\temp\$outputFolderName" If(!(test-path $outputpath)) { New-Item -ItemType Directory -Force -Path $outputpath | Out-Null } $computers = Get-Content -path C:\Temp\svrs.txt $report = @() foreach ($computer in $computers) { $Ping = Test-Connection -ComputerName $computer -Quiet -count 2 # 统一使用CimInstance调用,替代已过时的WMI查询命令 $wmi = Get-CimInstance win32_bios -ComputerName $computer -ErrorAction SilentlyContinue if ($wmi) { $WMIResult = 'Server IS Contactable' # 初始化空数组,存储当前设备所有用户的配置文件检测结果 $profileResultList = @() foreach ($userName in $targetUsers) { $userProfile = Get-CimInstance -ComputerName $computer -Class Win32_UserProfile -ErrorAction SilentlyContinue | Where-Object { $_.LocalPath.split('\')[-1] -eq $userName } if ($userProfile) { # 单用户结果追加到数组,不覆盖已有数据 $profileResultList += "$userName Exists" } else { $profileResultList += "$userName No Profile" } } # 所有用户检测完成后,统一按要求格式拼接字符串 $profileexists = $profileResultList -join ' ; ' $tempreport = [PSCustomObject]@{ ComputerName = $computer.ToUpper() WMI_Connection = $WMIResult Pingable = $Ping Profile_Search = $profileexists } $report += $tempreport } else { $WMIResult = 'Server NOT Contactable' $tempreport = [PSCustomObject]@{ ComputerName = $computer.ToUpper() WMI_Connection = $WMIResult Pingable = $Ping Profile_Search = $null } $report += $tempreport } } $CSVFileName = 'ProfileAudit ' + $(Get-Date -f dd-MM-yyyy) + '.csv' # 增加UTF8编码参数,避免特殊字符乱码 $report | Export-Csv $outputpath\$CSVFileName -NoTypeInformation -Encoding UTF8
关键修改说明
- 将AD组
TestDisabledUsers的成员查询移到计算机遍历循环外部,整个脚本仅执行1次AD查询,服务器数量较多时执行速度提升明显 - 每检测一台设备前初始化空数组
$profileResultList,专门存储该设备上所有用户的配置文件检测状态,避免变量覆盖 - 遍历单个用户时仅做结果追加,不直接给最终拼接变量赋值
- 所有用户检测完成后,再使用
-join ' ; '将数组内的多个结果拼接为符合要求的字符串,完全匹配预期输出格式 - 替换原脚本中已过时的
Get-WmiObject(别名gwmi)为Get-CimInstance,和后续用户配置文件查询的调用方式保持一致,兼容性更好 - CSV导出增加UTF8编码参数,避免出现字符乱码问题
- 保留原脚本所有业务逻辑,输出列结构、WMI/Ping判断规则、输出路径生成规则完全符合需求
内容的提问来源于stack exchange,提问作者SvrEngineer
相关产品推荐
相关产品推荐

