如何在 PowerShell 中跨列添加数字?

How can I add numbers across columns in PowerShell?

在我的 .csv 文件中,我有四列数字定义如下:
aIN = $item1.IN
aOUT = $item1.OUT
bIN = $item2.IN
bOUT = $item2.OUT

数字本身是整数和小数的混合体。我正在尝试使用以下方法查找总入列和总出列:
total-IN = aIN + bIN
total-OUT = aOUT + bOUT

假设我有...
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

我想要的是...
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

我的方法无效。预先感谢您的帮助!

使用

  • a Select-Object 追加总列数
  • 使用 ForEach 遍历源代码
  • 并投射为替身

$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

你也可以用 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