Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Compare-Object Format Output

Here is the script that I wrote:

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

And this is my output:

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

Is it possible for me to format my output in such a way that I can change the headers of each column?

And instead of => and <= I could give which file the differences are actually found in?

Here is the kind of output I am looking for:

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

I'm still quite new to PowerShell so if you could explain your answer that would be great, just so I can understand what is actually going on.

I am also trying to make this "dummy proof" so that anyone can just compare two text files, without any further input.

Any help would be greatly appreciated!

like image 643
BRBT Avatar asked Mar 06 '14 16:03

BRBT


2 Answers

Something like this, maybe?

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
like image 132
mjolinor Avatar answered Sep 22 '22 23:09

mjolinor


change this:

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

with this:

Compare-Object $compareOne $compareTwo  | 
ft inputobject, @{n="file";e={ if ($_.SideIndicator -eq '=>') { "$file2" }  else { "$file1" } }} | Out-File $outFile
like image 38
CB. Avatar answered Sep 22 '22 23:09

CB.