How can I write a file in PowerShell without adding a newline at the end?

August 31, 2025 1 answer
Asked by CuriousCod3r
Hey everyone, I'm working on a PowerShell script that retrieves an OpenSSH private key and saves it to a specific location for MobaXterm to use when logging in. The issue I'm facing is that both Out-File and Set-Content are adding a carriage return (0x0D) and a newline character (0x0A) at the end of the file, which makes the key invalid for MobaXterm. I've tried using the -NoNewLines parameter, but that ends up removing the necessary newlines within the key itself. I'm looking for a way to write my string to a file without any additional newlines at the end. I've considered splitting the input into an array and writing each element separately with -NoNewLines, but I'm wondering if there's a simpler method to remove just those last two bytes. Any ideas? Thanks!

Answers

PowerShellNinja
You know, both Set-Content and Out-File will only add what they receive. If there's an extra line, it's likely part of the string itself. Have you tried using .trim()? That might help with the spaces in your input.

DebugKing: Iโ€™ve been testing this all day, and itโ€™s not the case. If you run `โ€˜testโ€™ | Set-Content -Path test.txt`, you'll see the file length is longer by 2 bytes due to 0x0D and 0x0A added at the end. I checked it in a hex editor, and it definitely shows those extra bytes.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions