使用Windows Powershell从2个csv文件中减去数值,并生成一个显示附加方差列的输出文件

ddrv8njm  于 2023-03-30  发布在  Shell
关注(0)|答案(1)|浏览(124)

我有2个csv文件与数据值对某些参数如下
文件1

Entity Account Amount
100    1001    $100
100    1004    $300
101    1002    $200

文件2

Entity Account Amount
100    1001    $100
100    1004    $200
101    1002    $200
101    1005    $500

使用上述2个文件,我需要产生另一个csv文件,其中有金额列,按文件1和文件2,也是一个方差列显示在2个文件的差异如下
输出文件

Entity Account Amount as per file1  Amount as per file2 Variance Amount
100    1001    $100                  $100                 0 
100    1004    $300                  $200                 $100
101    1002    $200                  $200                 0  
101    1005    $0  (blank record)    $500                 ($500)

我知道我们有比较对象命令,我们可以找到独特的/diff记录b/w2 csv文件使用相同的,我成功地做到了。但是,请让我知道,如果我们可以合并文件,并通过PowerShell产生一个方差文件如上所述
我是新的脚本,所以任何指针将是有益的
我尝试了如下的compare-object来从2个文件中获取唯一的记录

PS C:\Users\Daman>  compare-object (Get-Content C:\File1.csv) (Get-Content C:\File2.csv)
v8wbuo2f

v8wbuo2f1#

PS中没有join(也没有左外join),所以最好使用for循环。参见下面的代码:

$filename1 = "c:\temp\test.csv"
$filename2 = "c:\temp\test1.csv"

$temp = Import-CSV -Path $filename1
#make $temp expandable
#$csv1 = [System.Collections.ArrayList]::new()
$csv1 = [System.Collections.ArrayList]$temp
$csv2 = Import-CSV -Path $filename2

#add column to $csv2 to indicate a match, rows with not match gets added later
foreach($row2 in $csv2)
{
   $row2 | Add-Member -NotePropertyName Found -NotePropertyValue $False
}
#add csv2 to csv1
foreach($row1 in $csv1)
{
   foreach($row2 in $csv2)
   {
      if(($row1.Entity -eq $row2.Entity) -and ($row1.Account -eq $row2.Account))
      {
         $row1 | Add-Member -NotePropertyName Amount2 -NotePropertyValue $row2.Amount
         $row2.Found = $True
         break;
      } 
   }
}
#add rows that are only in $csv2 to $csv1
foreach($row2 in $csv2)
{
   if(-not $row2.Found)
   {
         $newRow = New-Object -TypeName psobject
         $newRow | Add-Member -NotePropertyName Entity -NotePropertyValue $row2.Entity
         $newRow | Add-Member -NotePropertyName Account -NotePropertyValue $row2.Account
         $newRow | Add-Member -NotePropertyName Amount2 -NotePropertyValue $row2.Amount
         $csv1.Add($newRow)  | Out-Null
   }
}
foreach($row1 in $csv1)
{
   $amount1 = 0;
   if($row1.Amount -ne $null)
   {
      $amount1 = [int]$row1.Amount.Substring(1)
   }
   $amount2 = 0;
   if($row1.Amount2 -ne $null)
   {
      $amount2 = [int]$row1.Amount2.Substring(1)
   }
   $variance = $amount1 - $amount2
   if($variance -lt 0)
   {
      $row1 | Add-Member -NotePropertyName Variance -NotePropertyValue ('($' + [Math]::abs($variance) + ')')
   }
   else
   {
      $row1 | Add-Member -NotePropertyName Variance -NotePropertyValue ('$' + $variance)
   }
}
$csv1 | Format-Table

结果

Entity Account Amount Amount2 Variance
------ ------- ------ ------- --------
100    1001    $100   $100    $0
100    1004    $300   $200    $100
101    1002    $200   $200    $0
101    1005           $500    ($500)

相关问题