How to convert a file LF to CRLF

Is there a PowerShell command (or anything else) to convert the line endings within a text file from Unix-style (line-feed only) to Windows-style (carriage-return and line-feed), in place, without changing anything else (apart from modification date, which would be OK)? In some *nix systems, there is a command called unix2dos.

Have you attempted to search the interwebs? Using “powershell convert lf to crlf” there were many results


Yeah, sure.

$FilePath = "C:\Test\File.txt"
(Get-Content -Raw -Path $FilePath) -replace '\n','\r\n' | Set-Content -Path $FilePath


[quote quote=177891]Yeah, sure.

<textarea class="ace_text-input" wrap="off" autocorrect="off" autocapitalize="off" spellcheck="false" style="opacity: 0; height: 18px; width: 6.59781px; left: 44px; top: 0px;"></textarea>
$FilePath = "C:\Test\File.txt"
(Get-Content -Raw -Path $FilePath) -replace '\n','\r\n' | Set-Content -Path $FilePath

You can’t use regex in the 2nd replace argument, plus set-content adds an extra newline unless you turn it off.

# unix2dos
(Get-Content -Raw -Path $FilePath) -replace '\n',"`r`n" | Set-Content -Path $FilePath -NoNewline

I also posted a similar thing here with an extra regex negative lookbehind. powershell - Unix newlines to Windows newlines (on Windows) - Stack Overflow

What happened to quoting in the forum?

Thank you, Joel and js! That works. I’m new to this forum – is there a way to credit you with helpful posts or problem solutions?

No, but you can up arrow me on stackoverflow.