Add Column to CSV Windows PowerShell

2019-01-07 17:22发布

问题:

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,c
3,5

After

column1, column2, column3
1,b, setvalue
2,c, setvalue
3,5, setvalue

I can't find anything on this if anybody could point me in the right direction that would be great. Sorry very new to Power Shell.

回答1:

Here's one way to do that using Calculated Properties:

Import-Csv file.csv | 
Select-Object *,@{Name='column3';Expression={'setvalue'}} | 
Export-Csv file.csv -NoTypeInformation

You can find more on calculated properties here: http://technet.microsoft.com/en-us/library/ff730948.aspx.

In a nutshell, you import the file, pipe the content to the Select-Object cmdlet, select all exiting properties (e.g '*') then add a new one.



回答2:

The ShayLevy's answer also works for me!

If you don't want to provide a value for each object yet the code is even easier...

Import-Csv file.csv | 
Select-Object *,"column3" | 
Export-Csv file.csv -NoTypeInformation


回答3:

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?



回答4:

create a csv file with nothin in it

$csv >> "$PSScriptRoot/dpg.csv"

define the csv file's path. here $psscriptroot is the root of the script

$csv = "$PSScriptRoot/dpg.csv"

now add columns to it

$csv | select vds, protgroup, vlan, ports | Export-Csv $csv