导入CSV后,向阵列添加更多数据

时间:2016-07-27 18:58:45

标签: csv powershell

我正在尝试从CSV文件导入数据,然后向该对象添加其他标头和数据。 示例:CSV包含

firstname,lastname,e-mail,telephone
john,doe,jd@jd.com,3015551212

我想添加一个值为reason的字段duplicate

最后,我想将所有更新的信息导出到另一个CSV文件。

$completelist = '.\NZ-CompleteList.csv'
Import-Csv -Path $CompleteList |
    Group-Object TelephoneExtension |
    Where-Object {$_.Count -gt 1} |
    Select-Object -ExpandProperty Group

1 个答案:

答案 0 :(得分:0)

几乎就在那里:

$completelist = '.\NZ-CompleteList.csv'
import-csv -path $CompleteList | Group-Object TelephoneExtension | Where-object {$_.count -gt 1} | Select-Object -ExpandProperty Group | Select-Object *,@{n='Reason';e={'Duplicate'}} | Export-CSV Duplicates.csv -NoTypeInformation

编辑:

好。然后

$completelist = '.\NZ-CompleteList.csv'
$original = import-csv -path $CompleteList
$export = $original | Group-Object TelephoneExtension | Where-object {$_.count -gt 1} | Select-Object -ExpandProperty Group | Select-Object *,@{n='Reason';e={'Duplicate'}}
$export += $original | Group-Object TelephoneExtension | Where-object {$_.count -eq 1} | Select-Object -ExpandProperty Group | Select-Object *,@{n='Reason';e={'Unique'}}
$export | Export-CSV Updated.CSV -NoTypeInformation

如果你想保留排序......

$completelist = '.\NZ-CompleteList.csv'
$original = import-csv -path $CompleteList

$Original | Select-Object *,@{n='Reason';e={$t = $_.TelephoneExtension; IF (($Original | ?{$_.TelephoneExtension -eq $t}).count -gt 1) {"Duplicate"} ELSE {"Unique"}}} | Export-CSV Updated.CSV -NoTypeInformation

保留排序并更新原始文件

$completelist = '.\NZ-CompleteList.csv'
$original = import-csv -path $CompleteList

$export = $Original | Select-Object *,@{n='Reason';e={$t = $_.TelephoneExtension; IF (($Original | ?{$_.TelephoneExtension -eq $t}).count -gt 1) {"Duplicate"} ELSE {"Unique"}}}
$export | export-csv $completelist -notypeinformation

根据我的经验,您无法读取文件的内容并在同一行上覆盖该文件。