A Blog on Wndows Server and Microsoft Exchange by Thomas Pätzold

UNIX2DOS using Powershell

leave a comment »

Today I was asked to convert a file from the UNIX fileformat to the DOS fileformat.
As you probably know the format is different in the last character of each line. The DOS format ends with a carriage return (Cr) line feed (Lf) character whereas the UNIX format uses the line feed (Lf) character.
So this is a very simple task using Powershell

get-content <filename> |% {$_.replace("`n", "`r`n")} | out-file -filepath <new filename>

Remember the “%” means foreach-object. So this oneliner runs through the whole file and replaces the Lf with the CrLf character.

If you need a solution to use in a pipeline like the UNIX2DOS Unix command write a function that accepts the input from pipeline. The function looks like

function unix2dos{
param([Parameter(Mandatory=$true, ValueFromPipeline=$True)][String]$line)
begin {}
process {
$result = [string]$line.replace("`n","`r`n")
end {}

Call this function like:

get-content <filename> | unix2dos | out-file -filepath <new filename>

If you put this function in your Powershell profile, you are able to use is anytime anywhere.


Written by Thomas Pätzold

January 21, 2013 at 9:59 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: