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

0
1
Asked By CuriousCod3r On

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!

1 Answer

Answered By PowerShellNinja On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.