PowerShell用Export-CSV cmdlet导出CSV异常如何解决
导出失效的核心原因
- 原脚本里的
Write-Host仅会把内容打印到控制台,不会进入PowerShell的对象传递管道,Export-Csv根本捕获不到这部分输出,导出的文件里不会显示对应计算机名。 - 循环内直接输出的软件查询结果没有绑定所属服务器的属性,就算强行管道导出,最后拿到的CSV也分不清哪条软件装在哪台机器上,遇到WMI连接失败的设备时,异常信息还会打乱CSV结构,导致文件打不开或者内容错乱。
- 额外提醒:调用
Win32_Product类会触发目标设备上所有MSI格式安装包的一致性校验,生产环境执行可能触发意外的软件自动修复、配置重置,建议替换为读取注册表的方式查询已安装软件,稳定性更高。
可正常导出CSV的修正脚本
# 配置CSV文件导出路径 $exportPath = "C:\temp\ServerInstalledSoftware.csv" # 查询AD中所有启用的Windows Server设备 $Computers = Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true"' -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address | Sort-Object -Property Name # 初始化数组存储全量查询结果 $allSoftwareList = @() foreach ($Computer in $Computers) { Write-Host "正在查询设备:$($Computer.Name)" try { # 查询目标设备的已安装软件,捕获连接异常 $softwareList = Get-WmiObject -Class Win32_Product -ComputerName $Computer.Name -ErrorAction Stop | Select-Object Name, Version, Vendor, Caption | Sort-Object -Property Name,Vendor,Version,Caption # 给每条软件记录追加所属服务器的标识属性 foreach ($software in $softwareList) { $software | Add-Member -NotePropertyName "ComputerName" -NotePropertyValue $Computer.Name -Force $software | Add-Member -NotePropertyName "OperatingSystem" -NotePropertyValue $Computer.Operatingsystem -Force $software | Add-Member -NotePropertyName "OSVersion" -NotePropertyValue $Computer.OperatingSystemVersion -Force $software | Add-Member -NotePropertyName "IPv4Address" -NotePropertyValue $Computer.IPv4Address -Force $allSoftwareList += $software } } catch { Write-Warning "设备 $($Computer.Name) 连接失败:$($_.Exception.Message)" # 记录连接失败的设备,避免遗漏 $failRecord = [PSCustomObject]@{ ComputerName = $Computer.Name OperatingSystem = $Computer.Operatingsystem OSVersion = $Computer.OperatingSystemVersion IPv4Address = $Computer.IPv4Address Name = "WMI连接查询失败" Version = $null Vendor = $null Caption = $null } $allSoftwareList += $failRecord } Write-Host "`n" } # 统一导出为CSV,指定UTF8编码避免中文乱码,去掉多余的类型头信息 $allSoftwareList | Export-Csv -Path $exportPath -Encoding UTF8 -NoTypeInformation Write-Host "查询完成,结果已导出至:$exportPath"
使用说明
- 执行前先确认
$exportPath配置的目录存在,也可以根据需要修改为自定义的存储路径。 - 脚本加了异常捕获逻辑,单台服务器连接失败不会中断整体查询,失败的记录也会写入CSV方便后续排查。
- 导出的CSV每条记录对应一台服务器上的一个已安装软件,同时附带了对应服务器的名称、操作系统版本、IP等信息,可直接用于筛选统计。
内容的提问来源于stack exchange,提问作者Tech Guy
相关产品推荐
相关产品推荐

