2

I'm trying to compare the contents of a text file with a string. Sounds simple, but no luck!

$mystring = @'
hello
goodbye
'@

set-content c:\temp\file.txt $mystring

if (Test-Path "c:\temp\file.txt") {
    $myfile = Get-Content "c:\temp\file.txt" -raw
    if ($myfile -eq $mystring) {
        write-host 'File same'
    }
    else {
        write-host 'File different'
    }
}
else {
    write-host 'No file'
}

Write-Host $mystring.Length
Write-Host $myfile.Length

Output

File different
14
16

The lengths of the two string are different and when you open the file, there's a new line at the bottom which is where I'm presuming the extra 2 characters in the length are coming from.

What am I missing?

OffColour
  • 33
  • 1
  • 4
  • Possible duplicate of: https://stackoverflow.com/questions/45266461/set-content-appends-a-newline-line-break-crlf-at-the-end-of-my-file – SAS Aug 05 '19 at 11:06

3 Answers3

1

Append -NoNewline in set-content command

so your full line will be

Set-Content "c:\temp\file.txt" $mystring -NoNewline
Nirav Mistry
  • 949
  • 5
  • 15
1

You could remove trailing newline characters with String.Trim() before comparing:

$myfile = (Get-Content "c:\temp\file.txt" -Raw).Trim()
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • The extra newline would still be in the file, which might not be expected, since it's not in the original string. – SAS Aug 05 '19 at 11:39
0

Possible solution:

Add parameter -NoNewline

Making it: set-content c:\temp\file.txt $mystring -NoNewline

Possible duplicate of:

Set-Content appends a newline (line break, CRLF) at the end of my file

Explanation:

https://blogs.msdn.microsoft.com/jmanning/2007/05/23/powershell-gotcha-of-the-day-set-content-adds-newlines-by-default/

SAS
  • 3,943
  • 2
  • 27
  • 48