问题
I have a requirement to add data to the last column of a CSV file. The test file I have looks like:
NAME,AGE,OFFICE,DEPT,SKILL jack,24,IBM,Retail tom,32,MS,BFSI SAM,44,MGR,Test
I have managed to parse the CSV but then adding data to the last column "SKILL" is difficult. The requirement is to add the word 'Java' to the last column on each row
NAME,AGE,OFFICE,DEPT,SKILL jack,24,IBM,Retail,Java tom,32,MS,BFSI,Java SAM,44,MGR,Test,Java
Please note that the value added to the last column remains the same across rows.
回答1:
You can change the value of SKILL
property of the imported objects, and export to CSV file by this:
Import-Csv test.txt |
ForEach-Object {$_.SKILL = "Java"; $_} |
Export-Csv test_out.txt -NoTypeInformation
However Export-Csv
adds quotation marks around the values, so test_out.txt
would look like this:
"NAME","AGE","OFFICE","DEPT","SKILL"
"jack","24","IBM","Retail","Java"
"tom","32","MS","BFSI","Java"
"SAM","44","MGR","Test","Java"
Maybe you should simply add ",Java
" to the end of each line second line onwards:
Get-Content test.txt |
ForEach-Object { if($_.ReadCount -gt 1) { "$($_),Java" } else { $_ } } |
Out-File test_out.txt
回答2:
You could simply create an object that contains the current csv-data and extend that object with the string Java
like so:
$results = @() # Empty array to store new created rows in
$csv = Import-Csv "$PSScriptRoot\csvfile.csv"
foreach ($row in $csv) {
$properties = [ordered]@{
NAME = $row.NAME
AGE = $row.AGE
OFFICE = $row.OFFICE
DEPT = $row.DEPT
SKILL = "Java"
}
# insert the new row as an object into the results-array
$results += New-Object psobject -Property $properties
}
# foreach-loop filled the results-array - export it as a CSV-file
$results | Export-Csv "new-file.csv" -NoTypeInformation
来源:https://stackoverflow.com/questions/54197624/how-to-add-data-to-last-column-of-csv-using-powershell