Compare objects in an if statement Powershell

Alex McKenzie picture Alex McKenzie · Nov 18, 2013 · Viewed 22.6k times · Source

I'm trying to compare two files and if their content matches I want it to preform the tasks in the if statement in Powershell 4.0

Here is the gist of what I have:

$old = Get-Content .\Old.txt
$new = Get-Content .\New.txt
if ($old.Equals($new)) {
 Write-Host "They are the same"
}

The files are the same, but it always evaluates to false. What am I doing wrong? Is there a better way to go about this?

Answer

Keith Hill picture Keith Hill · Nov 18, 2013

Get-Content returns an array of strings. In PowerShell (and .NET) .Equals() on an array is doing a reference comparison i.e. is this the same exact array instance. An easy way to do what you want if the files aren't too large is to read the file contents as a string e.g.:

$old = Get-Content .\Old.txt -raw
$new = Get-Content .\Newt.txt -raw
if ($old -ceq $new) {
    Write-Host "They are the same"
}

Note the use of -ceq here to do a case-sensitive comparison between strings. -eq does a case-insensitive compare. If the files are large then use the new Get-FileHash command e.g.:

$old = Get-FileHash .\Old.txt
$new = Get-FileHash .\New.txt
if ($old.hash -eq $new.hash) {
    Write-Host "They are the same"
}