比较对象输出格式

时间:2016-03-17 19:06:40

标签: powershell compare compareobject

我需要比较两个CSV文件。这两者都可能(或可能不)包含额外的分隔字段(通过“|”字符分隔),如下所示:

(new.csv)
Title,Key,Value
Jason,Son,Hair=Red|Eyes=Blue
James,Son,Hair=Brown|Eyes=Green
Ron,Father,Hair=Black
Susan,Mother,Hair=Black|Eyes=Brown|Dress=Green

(old.csv)
Title,Key,Value
Jason,Son,Hair=Purple|Eyes=Blue
James,Son,Hair=Brown|Eyes=Green
Ron,Father,Hair=Purple
Susan,Mother,Hair=Black|Eyes=Brown|Dress=Blue

当我尝试比较两个文件时,我的问题出现了......

$fileNew = "new.csv"
$fileOld = "old.csv"
$fileDiffOutputFile = "diff.txt"

$csvNewLog = (Import-CSV ($fileNew))
$csvOldLog = (Import-CSV ($fileOld))

$varDifferences = Compare-Object $csvOldLog $csvNewLog -property Title,Value

$varDifferences | Group-Object -Property Title | % {New-Object -TypeName PSObject -Property @{ NewValue=($_.group[0].Value); Title=$_.name; OldValue=($_.group[1].Value) } } | Out-File $fileDiffOutputFile -Append

导致此输出:

(diff.txt)
OldValue                   Title                      NewValue                 
--------                   -----                      --------                 
Hair=Purple|Eyes=Blue      Jason                      Hair=Red|Eyes=Blue       
Hair=Purple                Ron                        Hair=Black               
Hair=Black|Eyes=Brown|D... Susan                      Hair=Black|Eyes=Brown|...

有些值不可避免地会超出列的最大长度,就像上面的Susan一样。

所以,我的问题可能有几个我能想到的解决方案:

  1. 是否有更简单的方法来隔离值,以便我只提取更改的值,而不是整个分隔值的字符串?
  2. 如果没有,是否可以让格式显示整个字符串(包括分隔字符串的未更改值部分)?

1 个答案:

答案 0 :(得分:1)

如果您在最后一行中添加了format-table -wrap,请执行此操作?

$fileNew = "new.csv"
$fileOld = "old.csv"
$fileDiffOutputFile = "diff.txt"

$csvNewLog = (Import-CSV ($fileNew))
$csvOldLog = (Import-CSV ($fileOld))

$varDifferences = Compare-Object $csvOldLog $csvNewLog -property Title,Value

$varDifferences | Group-Object -Property Title | % {New-Object -TypeName PSObject -Property @{ NewValue=($_.group[0].Value); Title=$_.name; OldValue=($_.group[1].Value) } } | Format-Table -wrap | Out-File $fileDiffOutputFile -Append