user310291
user310291

Reputation: 38180

Is it possible to create a new csv column with calculation while importing in Powershell?

I'd like to be able to do something like This except -AddColumn is fictitious syntaxe :

Import-Csv in.csv -header Date,Time,O,H,L,C,V|select * -AddColumn median %{$_.median=($_.H + $_.L)/2}

What would be the real syntax or how to do it the easiest way ?

data file :

2015.08.09,20:45,1.09538,1.09546,1.09522,1.09524,74
2015.08.09,20:50,1.09523,1.09537,1.09505,1.09523,110
2015.08.09,20:55,1.09524,1.09546,1.09520,1.09526,165
2015.08.09,21:00,1.09526,1.09526,1.09495,1.09497,141

Upvotes: 0

Views: 105

Answers (1)

Matt
Matt

Reputation: 46700

Foreach-Object and Add-Member come to mind but a simpler solution would be to use a calculated property.

Import-Csv in.csv -header Date,Time,O,H,L,C,V | select *, @{Name="median";Expression={([double]$_.H + [double]$_.L)/2}}

Don't forget to cast your numbers for mathematical calculations. Before it was trying to do something like this:

($_.H + $_.L)/2
("1.09538" + "1.09524")/2
(1.095381.09524)/2 # < that would not compute

Upvotes: 3

Related Questions