2014-03-06 156 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