【问题标题】:My Powershell loop is overwriting the previous excel entry. Using Export-CSV -append duplicates entries我的 Powershell 循环正在覆盖以前的 excel 条目。使用 Export-CSV -append 重复条目
【发布时间】:2026-01-03 02:00:01
【问题描述】:

Powershell 绝对不是我的“优势”之一,但我偶尔会尝试编写脚本来自动执行手动任务。无论如何,这是我的问题。该脚本按原样工作,并将导出一个 csv 文件并按主机名标题排序。我的问题是必须有更好的方法吗?

#Clear the output screen
cls

#set the working directory to where the script and text files are located (must be same directory)
$scriptdir = Split-Path -Parent $PSCommandPath
cd $scriptdir

#set fileNamePaths for Export-Csv No Sort and Sorted to excel
$FilePathNS = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll_NoSort.csv"
$FilePathSort = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll.csv"

#set up the ip subnet import
$path = ".\EnclosureSubnets.txt"
$ip = Get-Content $path

#Loop to find OA information
foreach ($subnet in $ip) {

    $OAS = Find-HPOA $subnet -Timeout 250 -Verbose
    $OAS | where {$_.Role -eq "Active"} | Export-Csv -NoTypeInformation -Append $FilePathNS
}

#Sort AOInfoAll.csv by hostname
Import-Csv $FilePathNS | Sort-Object Hostname | Export-Csv $FilePathSort -NoTypeInformation

如果我取出追加,那么循环将覆盖前一个条目,我最终只会得到 2 个 IP 和 2 个主机名。 Append 解决了这个问题,但是当我再次运行脚本时,我得到了重复/重复的条目。

另外,我尝试在循环中使用 Sort-Object 主机名,但它只在写入时对每个单独的条目进行排序。这是一个示例(IP 和主机名组成):

IP                  Hostname
192.168.1.10        chassis03
192.168.1.12        chassis05
192.168.2.16        chassis01
192.168.2.18        chassis02
192.168.3.14        chassis07
192.168.3.16        chassis08

所以,当我的脚本有效时,我想从“专业人士”那里得到一些反馈,提前谢谢!

【问题讨论】:

    标签: sorting csv powershell append overwrite


    【解决方案1】:

    不要在循环中导出,而是在一个变量中捕获所有 OAS 并在输出到 CSV 之前对其进行排序。

    foreach ($subnet in $ip) {
    
        [array]$OAS += Find-HPOA $subnet -Timeout 250 -Verbose
    
    }
    
    $OAS | Where{$_.Role -eq 'Active'} | Sort Hostname | Export-Csv $FilePathSort -NoTypeInformation
    

    这大大减少了磁盘读取/写入的次数。

    【讨论】:

      最近更新 更多