Compare objects in if Powershell expression

I'm trying to compare two files, and if their contents match, I want it to perform tasks in an 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"
}

Files are the same, but always evaluated as false. What am I doing wrong? Is there a better way to do this?

+4
source share
1 answer

Get-Contentreturns an array of strings. In PowerShell (and .NET) .Equals(), a comparative comparison is performed in the array, i.e. This is the exact same array instance. An easy way to do what you want if the files are not too large is to read the contents of the file as a string, for example:

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

-ceq , . -eq . , Get-FileHash, :

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

All Articles