Add Column to CSV Windows PowerShell

后端 未结 5 1511
野的像风
野的像风 2020-11-28 10:52

I have a fairly standard csv file with headers I want to add a new column & set all the rows to the same data.

Original:

column1, column2
1,b
2         


        
5条回答
  •  隐瞒了意图╮
    2020-11-28 11:30

    For some applications, I found that producing a hashtable and using the .values as the column to be good (it would allow for cross reference validation against another object that was being enumerated).

    In this case, #powershell on freenode brought my attention to an ordered hashtable (since the column header must be used).

    Here is an example without any validation the .values

    $newcolumnobj =  [ordered]@{}
    #input data into a hash table so that we can more easily reference the `.values` as an object to be inserted in the CSV
    $newcolumnobj.add("volume name", $currenttime)
    
    #enumerate $deltas [this will be the object that contains the volume information `$volumedeltas`)
    #  add just the new deltas to the newcolumn object
    foreach ($item in $deltas){ 
      $newcolumnobj.add($item.volume,$item.delta)
    }
    
    $originalcsv = @(import-csv $targetdeltacsv)
    
    #thanks to pscookiemonster in #powershell on freenode
    for($i=0; $i -lt $originalcsv.count; $i++){
      $originalcsv[$i] | Select-Object *, @{l="$currenttime"; e={$newcolumnobj.item($i)}}
    }
    

    Example is related to How can I perform arithmetic to find differences of values in two CSVs?

提交回复
热议问题