PowerShell Foreach输出导出CSV问题求助
解决PowerShell导出AD计算机信息到CSV的问题
嘿Victor,我瞅了下你的代码,问题很明确:你在循环里执行Get-ADComputer的时候,结果只是输出到了PowerShell控制台,并没有被传递给Export-CSV命令,所以最后导出的文件是空的。下面给你几种可行的解决办法:
方法一:收集结果到变量后导出
这种方式适合需要后续对结果做额外处理的场景,先把所有AD计算机对象存到一个数组里,再统一导出:
# 读取目标计算机列表 $computers = Get-Content -Path C:\folder\file.csv # 初始化空数组用于存储结果 $computerDetails = @() foreach ($computer in $computers) { # 将每台计算机的信息添加到结果数组中 $computerDetails += Get-ADComputer $computer -Properties CanonicalName } # 导出到CSV,-NoTypeInformation可以去掉文件开头的类型注释,让CSV更干净 $computerDetails | Export-CSV -Path c:\folder2\finalfile.csv -NoTypeInformation
方法二:直接通过管道传递循环结果
这种方式更简洁,不需要额外变量,循环输出的结果直接通过管道传给Export-CSV:
$computers = Get-Content -Path C:\folder\file.csv foreach ($computer in $computers) { Get-ADComputer $computer -Properties CanonicalName } | Export-CSV -Path c:\folder2\finalfile.csv -NoTypeInformation
方法三:用ForEach-Object简化管道流程
这是最符合PowerShell管道风格的写法,直接把读取到的计算机名通过管道传给ForEach-Object,再把结果导出:
Get-Content -Path C:\folder\file.csv | ForEach-Object { Get-ADComputer $_ -Properties CanonicalName } | Export-CSV -Path c:\folder2\finalfile.csv -NoTypeInformation
另外提一句:你代码里的$numbers = @($computers)其实是多余的,Get-Content返回的本身就是字符串数组,不需要再转成数组啦。
内容的提问来源于stack exchange,提问作者Victor Antifries
相关产品推荐
相关产品推荐

