How to add data to last column of CSV using PowerS

2019-08-18 17:11发布

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.

2条回答
孤傲高冷的网名
2楼-- · 2019-08-18 17:58

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
查看更多
萌系小妹纸
3楼-- · 2019-08-18 18:03

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
查看更多
登录 后发表回答