Reputation: 10091
When I use gc
(get-content
) on the same file twice, and compare the strings using -eq
, why does it compare unequal?
$f = "C:\temp\test.txt"
echo Hello > $f
echo World >>$f # works if I uncomment this line
gc $f
# get the contents of the file twice and compare it to itself.
if ((gc $f) -eq (gc $f)) {
Write-Host "Hooray! The file is the same as itself."
} else {
Write-Host "Boo."
}
Prints Boo.
, unless I comment out the 3rd line - the problem only seems to occur with multiline files.
(obviously in reality I wouldn't compare the file to itself, in real life I'm comparing two files that might have identical content).
I'm running powershell 2.0.
Upvotes: 4
Views: 1255
Reputation: 68273
That will work if the file has only one line, but will fail if there are multiple lines because of the way -eq works as an array operator. For it to work as expected you need to compare both as scalar (single item) objects. One way to do this is to add the -Raw switch to Get-Content if you've got V3 or better.
if ((gc $f -raw) -eq (gc $f -raw))
That will read the entire file as a single, multi-line string.
To accomplish the same in V2:
if ([io.file]::ReadAllText($f)) -eq ([io.file]::ReadAllText($f))
or
if ([string](gc $f) -eq [string](gc $f))
Upvotes: 3