假设列数可以是随机的并且要排除的属性是已知的,您可以执行以下操作将数据解析为自定义对象:
Get-Content file.csv | Foreach-Object {
$count = 0 # Tracks column counts to split the row evenly
$cols = $_ -split ';'
# $headers gets the first half of the columns. $data gets the remainder.
$headers,$data = $cols.where({$count++ -lt $cols.count/2},'Split')
# Uses calculated properties to add your new properties. You will need to fill in your own logic since you provided none here.
($headers -join ';'),($data -join ';') | ConvertFrom-Csv -Delimiter ';' |
Select-Object *,@{n='Address';e={'Electric Avenue'}},@{n='Phone';e={'867-5309'}} -exclude example1,example2
}
如果 csv 文件中的所有数据都包含相同的标题,您可以使用 Export-Csv 从数据中创建正确的 CSV:
Get-Content file.csv | Foreach-Object {
$count = 0 # Tracks column counts to split the row evenly
$cols = $_ -split ';'
$headers,$data = $cols.where({$count++ -lt $cols.count/2},'Split')
($headers -join ';'),($data -join ';') | ConvertFrom-Csv -Delimiter ';' |
Select-Object *,@{n='Address';e={'Electric Avenue'}},@{n='Phone';e={'867-5309'}} -exclude example1,example2
} | Export-Csv output.csv -NoType
如果每个单独的行可能有不同数量的列,则您可能需要每行一个 CSV 文件,除非您解析所有数据并确定所有可能的列名。如果您想保持与源相同的格式但只想操作列和数据,您可以执行以下操作,这将适用于不同数量的列:
Get-Content file.csv | Foreach-Object {
$count = 0 # Tracks column counts to split the row evenly
$cols = $_ -split ';'
$headers,$data = $cols.where({$count++ -lt $cols.count/2},'Split')
$newObj = ($headers -join ';'),($data -join ';') | ConvertFrom-Csv -Delimiter ';' |
Select-Object *,@{n='Address';e={'Electric Avenue'}},@{n='Phone';e={'867-5309'}} -exclude example1,example2
"{0};{1}" -f ($newObj.psobject.properties.name -join ';'),($newObj.psobject.properties.value -join ';')
}