Powershell比较对象格式输出

时间:2014-03-06 16:17:47

标签: powershell output compareobject

这是我写的脚本:

function Compare {

    $file1 = Read-Host "Please enter the path of the first file you would like to compare"
    $file2 = Read-Host "Please enter the path of the second file you would like to compare"

    $outFile = Read-Host "Please enter the path to where you would like your output file."

    Try{
        $compareOne = Get-Content $file1
        $comparetwo = Get-Content $file2
    } 
    Catch{
        Write-Host "The path you entered is either invalid or the file does not exist. "    
    }

    Write-Host "Beginning comparison"
    Compare-Object $compareOne $compareTwo  | Out-File $outFile
    Write-Host "Complete!"
}

Compare

这是我的输出:

InputObject | SideIndicator
------------|--------------
   Value1   |    <=
   Value2   |    <=
   Value3   |    =>
   Value4   |    =>

我是否可以格式化输出,以便我可以更改每列的标题?

而不是=><=我可以给出哪个文件实际找到的差异?

以下是我要找的输出类型:

   Value    |     File 
------------|--------------
   Value1   |    $file1
   Value2   |    $file2
   Value3   |    $file2
   Value4   |    $file1

我还是PowerShell的新手,所以如果你能解释一下你的答案会很棒,那么我就能理解实际发生了什么。

我也试图制作这个“虚拟证明”,这样任何人都可以比较两个文本文件,而无需任何进一步的输入。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:5)

这样的事,也许?

function compareCSV {

$file1 = Read-Host "Please enter the path of the first file you would like to compare"
$file2 = Read-Host "Please enter the path of the second file you would like to compare"

$outFile1 = Read-Host "Please enter the path to where you would like your output file."

Try{
    $compareOne = Get-Content $file1
    $comparetwo = Get-Content $file2
} 
Catch{
    Write-Host "The path you entered is either invalid or the file does not exist. "    
}

Write-Host "Beginning comparison"
$Compare = 
Compare-Object $compareOne $compareTwo

$compare | foreach  { 
      if ($_.sideindicator -eq '<=')
        {$_.sideindicator = $file1}

      if ($_.sideindicator -eq '=>')
        {$_.sideindicator = $file2}
     }

 $Compare | 
   select @{l='Value';e={$_.InputObject}},@{l='File';e={$_.SideIndicator}} |
   Out-File $outFile1

  Write-Host "Complete!"
}

compareCSV

答案 1 :(得分:4)

改变这个:

Compare-Object $compareOne $compareTwo  | Out-File $outFile

用这个:

Compare-Object $compareOne $compareTwo  | 
ft inputobject, @{n="file";e={ if ($_.SideIndicator -eq '=>') { "$file2" }  else { "$file1" } }} | Out-File $outFile