Friday, September 2, 2011

Convert flat file to xml using PowerShell

If you have a flat file and want to convert it to some other format like xml or CSV, this may help you. You need PowerShell to do this. All Windows 7 machines come with PowerShell installed, so for most people that shouldn't be a problem

We need some input to proceed, It can be a file or hard coded string or even clipboard. @" and "@helps you handle multiple lines without escaping it.

Now we have the input, lets go through line by line and spit out the output we want, `n is new line character for PowerShell. ` tells PowerShell that statement continues to next line. –f takes the format string and replaces {0} with input parameters.

If you are comfortable with one liners, you can do this, Move formatting string to separate statement, and use % for foreach.You get a nice readable online PowerShell script.