2

In my .csv file, I have four columns of numbers defined as follows:
aIN = $item1.IN
aOUT = $item1.OUT
bIN = $item2.IN
bOUT = $item2.OUT

The numbers themselves are a mix of integers and decimals. I am trying to find a total-IN column and a total-OUT column using the follows:
total-IN = aIN + bIN
total-OUT = aOUT + bOUT

Let's say I have...
aIN aOUT bIN bOUT
0.1 0.2 0.3 0.4
1 2 3 4
0.5 0.6 0.7 0.8
5 6 7 8

What I would like is...
aIN aOUT bIN bOUT total-IN total-OUT
0.1 0.2 0.3 0.4 0.4 0.6
1 2 3 4 4 6
0.5 0.6 0.7 0.8 1.2 1.4
5 6 7 8 12 14

My method is not working. Thanks in advance for your help!

2
  • 2
    "My method is not working" - what method? Commented Dec 13, 2018 at 18:21
  • total-IN = aIN + bIN and total-OUT = aOUT + bOUT Commented Dec 13, 2018 at 18:45

1 Answer 1

5

Using

  • a Select-Object to append total columns
  • iterate through source with a ForEach
  • and cast as a double

$CsvData = Import-Csv '.\testfile.csv' | Select-Object *,'total-IN','total-OUT'

ForEach ($Row in $CsvData) {
   $Row.'total-IN'  = [double]$Row.aIN  + $Row.bIN
   $Row.'total-OUT' = [double]$Row.aOUT + $Row.bOUT
}

$CsvData | Format-Table -AutoSize
$CsvData | Export-Csv .\your.csv -NoTypeInformation

You could also do with a calculated property

$CsvData = @"
aIN,aOUT,bIN,bOUT
0.1,0.2,0.3,0.4
1,2,3,4
0.5,0.6,0.7,0.8
5,6,7,8
"@ | ConvertFrom-Csv | Select-Object *,
    @{n='total-IN';e={[double]$_.aIN  + $_.bIN}},
    @{n='total-OUT';e={[double]$_.aOUT  + $_.bOUT}}

$CsvData | Format-Table -AutoSize
$CsvData | Export-Csv .\your.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.