2

我将 2 CSV 与 compare-object cmdlet 进行比较:

Compare-object $CSV1 $CSV2 -property Header, Value -passthru | sort-object Header

在比较了 2 个 CSV 之后,我得到了以下输出:

Header              Value           SideIndicator
-------             -----           -------------
String1             Value 1             <=
String1             Value 2             =>
String2             Value 3             <=
String2             Value 4             =>
String3             Value 5             =>
String4             Value 6             <=

我想将其重组为以下格式

Header1             Old Value       New Value
------              ---------       ---------
String1             Value 1         Value 2
String2             Value 3         Value 4
String3             NA              Value 5
String4             Value 6         NA

这在 powershell 中可行吗?

4

2 回答 2

2

你可以试试这个:

$a = Compare-Object (Import-Csv 'C:\temp\f1.csv')  (Import-Csv 'C:\temp\f2.csv')  -property Header,Value
$a | Group-Object -Property Header | % { New-Object -TypeName psobject -Property @{Header=$_.name;newValue=$_.group[0].Value;oldValue=$_.group[1].Value}}
于 2013-07-03T12:15:36.777 回答
1

正如我在评论中指出的那样,JPBlanc 的回答有一些缺陷。这是基于他的代码的改进:

$CSV1 = Import-Csv "C:\temp\f1.csv"
$CSV2 = Import-Csv "C:\temp\f2.csv"
$Diff = Compare-Object $CSV1 $CSV2 -property Header, Value
function Value-On-SideIndicator($Object, $SideIndicator) {
    $Group = $Object.Group | ? {$_.SideIndicator -eq $SideIndicator}
    if ($Group -ne $null) { $Group.Value } else { "NA" }
}
$Diff | Group-Object -Property Header | % {
    New-Object -TypeName psobject -Property @{
        Header = $_.Group[0].Value;
        newValue = Value-On-SideIndicator $_ "=>";
        oldValue = Value-On-SideIndicator $_ "<="
    }
} | Format-Table Header, oldAmount, newAmount -AutoSize

Powershell 7:(使用空合并运算符)

$CSV1 = Import-Csv "C:\temp\f1.csv"
$CSV2 = Import-Csv "C:\temp\f2.csv"
$Diff = Compare-Object $CSV1 $CSV2 -property Header, Value
$Diff | Group-Object -Property Header | % {
    New-Object -TypeName psobject -Property @{
        Header = $_.Group[0].Value;
        newValue = ($_.Group | ? {$_.SideIndicator -eq "=>"}).Value ?? "NA";
        oldValue = ($_.Group | ? {$_.SideIndicator -eq "<="}).Value ?? "NA"
    }
} | Format-Table Header, oldAmount, newAmount -AutoSize
于 2020-09-19T10:37:21.350 回答