Hey everyone! I'm working on a PowerShell script to retrieve an OpenSSH private key and save it for use with MobaXterm. While I can successfully write the file, I'm encountering an issue where both Out-File and Set-Content add extra carriage return and newline characters at the end, which is making the file unusable in MobaXterm. I know I can split the input into an array and use -NoNewLines to write each part separately, but that seems like overkill. Is there a simpler way to write my string to a file without those trailing newlines? Thanks!
5 Answers
Set-Content does still have a -NoNewline parameter, but it removes all new lines, so it's not ideal if you want to keep some intact.
When using Set-Content and Out-File, they only add what's in the string. If there's an extra line, it typically comes from your original input. Have you tried trimming the string before writing it out? That could help with any unwanted spaces or newlines.
I get what you're saying, but I've tested this extensively and it's definitely not the case. If you run ` 'test' | Set-Content -Path test.txt `, you'll see the file has extra characters. It's frustrating because they're not needed for the file structure.
I ran into this issue and found a solution! Try using `[System.IO.File]::WriteAllText($Path, 'string', [System.Text.Encoding]::UTF8)` instead of Out-File or Set-Content. It worked perfectly for me!
Yes, that’s a solid workaround! Someone else mentioned it too, and it really does do the trick without any extra characters.
If you aren't dealing with too many items, you can join your content with the new lines you want and then use -NoNewline. It can help you format it just right before final output.
You could also use this simple approach:
```powershell
$content = "This is the exact content I want"
[System.IO.File]::WriteAllText("output.txt", $content)
``` It’s straightforward and definitely gets the job done!
That’s a great solution! Thanks for sharing!
Exactly. It’s useful but not for this specific case where we just want to remove the last one.