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

PowerShell脚本导出CSV到两个路径时第二个文件为空的问题求助

PowerShell脚本导出CSV到两个路径时第二个文件为空的问题求助

嘿,这个问题我之前也踩过坑!核心原因是**Export-Csv默认不会把输入的对象传递到管道的下一个环节**——当你把数据管道给第一个Export-Csv之后,它就把数据“吃掉”了,后面的第二个Export-Csv根本没东西可以导出,自然就是空文件啦。

给你两种简单靠谱的解决方案:

方案一:先把结果存到变量(最直观推荐)

先把筛选、排序后的所有数据保存到一个变量里,再分别导出到两个CSV文件。这种方式逻辑清晰,后续调试也方便:

# 第一步:把处理好的结果存入变量
$filteredPrograms = Get-RemoteProgram -ComputerName (Get-Content -Path C:\PowerShell\complist.txt) -ExcludeProgram (Get-Content -Path C:\PowerShell\applist.txt) | 
    Where-Object {($_.ProgramName -notmatch 'KB\d+|Microsoft .NET|Microsoft Visual|Intel|Windows Driver Package')} | 
    Sort-Object -Property computer,programName

# 第二步:分别导出到两个CSV
$filteredPrograms | Export-Csv -Path C:\PowerShell\output.csv -NoTypeInformation
$filteredPrograms | Export-Csv -Path C:\PowerShell\outputappend.csv -NoTypeInformation -Append

方案二:用Tee-Object分流管道数据

如果你不想用变量,可以用Tee-Object命令,它能同时把管道数据写入文件,并且把数据继续传递到下游管道,这样第二个Export-Csv就能拿到数据了:

Get-RemoteProgram -ComputerName (Get-Content -Path C:\PowerShell\complist.txt) -ExcludeProgram (Get-Content -Path C:\PowerShell\applist.txt) | 
    Where-Object {($_.ProgramName -notmatch 'KB\d+|Microsoft .NET|Microsoft Visual|Intel|Windows Driver Package')} | 
    Sort-Object -Property computer,programName |
    Tee-Object -FilePath C:\PowerShell\output.csv | # 这里默认覆盖文件,要追加的话加-Append
    Export-Csv -Path C:\PowerShell\outputappend.csv -NoTypeInformation -Append

这里要提醒下:别想着给Export-Csv加-PassThru参数来传递数据,虽然它能把对象传下去,但会给CSV文件额外带上PowerShell对象的内部属性(比如PSPath、PSParentPath),导出的文件会不符合你的预期,所以不推荐这种方式。

备注:内容来源于stack exchange,提问作者Dan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 10:23:01