2014-03-06 82 views
3

这里是我写的剧本:Powershell的比较,对象格式输出

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的,所以如果你能解释一下你的答案将是巨大的,只是让我能理解什么是真正的继续。

我也试图做出这个“假证明”,以便任何人都可以比较两个文本文件,而不需要任何进一步的输入。

任何帮助将不胜感激!

回答

4

这样的事情,也许?

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 
+0

这正是我正在寻找的,但我只是想知道你是否可以请解释这里发生了什么:'$ Compare | select @ {l ='Value'; e = {$ _。InputObject}},@ {l ='File'; e = {$ _。SideIndicator}} | Out-File $ outFile1' – Zoxac

+1

这就是所谓的“计算属性”http://technet.microsoft.com/en-us/library/ff730948.aspx – mjolinor

3

改变这样的:

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