powershell foreach 显示重复结果

powershell foreach shows duplicate result

我使用 powershell 自动从 CSV 文件中提取所选数据。 我的 $target_servers 也包含两个相同的服务器名称,但每行的数据不同。

这是我的代码:

$target_servers = Get-Content -Path  D:\Users\Tools\windows\target_prd_servers.txt
foreach($server in $target_servers) {
    Import-Csv $path\Serverlist_Template.csv | Where-Object {$_.Hostname -Like $server} | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation
}

执行上面的代码后,它根据 TXT 文件提取 CSV 数据,但我的问题是有些结果是重复的。

我期待大约 28 个结果,但它给了我大约 49 个。

您可以将数据转换为对象数组,然后使用 select -Unique,如下所示:

$target_servers = Get-Content -Path  D:\Users\Tools\windows\target_prd_servers.txt

$data = @()
foreach($server in $target_servers) {
    $data += Import-Csv $path\Serverlist_Template.csv| Where-Object {$_.Hostname -Like $server}
}
$data | select -Unique | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation

只有当重复的行在每一列中具有相同的值时它才会起作用。如果没有,您可以将列名传递给 select,这对您很重要。例如:

$data | select Hostname -Unique | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation

它将为您提供唯一主机名列表。

如评论所述,-Append 是这里的罪魁祸首,您应该检查新添加的记录是否尚未出现在输出文件中:

# read the Hostname column of the target csv file as array to avoid duplicates
$existingHostsNames = @((Import-Csv -Path "$path/windows_prd.csv").Hostname)

$target_servers = Get-Content -Path  D:\Users\Tools\windows\target_prd_servers.txt
foreach($server in $target_servers) {
    Import-Csv "$path\Serverlist_Template.csv" |
         Where-Object {($_.Hostname -eq $server) -and ($existingHostsNames -notcontains $_.HostName)} | 
         Export-Csv -Path "$path/windows_prd.csv" -Append -NoTypeInformation
}