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?

1

3 Answers 3

1

Append -NoNewline in set-content command

so your full line will be

Set-Content "c:\temp\file.txt" $mystring -NoNewline
Sign up to request clarification or add additional context in comments.

Comments

1

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

$myfile = (Get-Content "c:\temp\file.txt" -Raw).Trim()

1 Comment

The extra newline would still be in the file, which might not be expected, since it's not in the original string.
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/

Comments

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.