6

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?

1 Answer 1

12

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works! What purpose does -raw have? It doesn't seem to work without it and I'm not sure why.
-Raw causes the Get-Content command to return the contents of the file as a single string instead of an array of strings corresponding to the lines in the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.