我正在将2 CSV与比较对象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中可行吗?
答案 0 :(得分: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}}
答案 1 :(得分:0)
正如my comment所指出的那样,JPBlanc's answer有一些缺陷。这是根据他的代码改进的:
$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