So I was at my monthly powershell script club working out how to format a text file. I did it the hard way ahead of time, using excel to move columns around and concatenate stuff. Then I used notepad++ to do the fiddly bits with the specific spaces and column spacing required. (Don’t ask, its for ingestion into a VERY old system)

I showed the guys the file format I get sent to me, then I showed them an example of the file output. Here’s the magic we came up with. Keep in mind they wanted me to condense this down to one line, but I’d rather keep it expanded so I can steal bits of it later. (yes, they gave me permission!)

This file takes in a file as an array, adds headers (not needed, but nice for get-member on the $data variable). The format command then parses the data and formats it to the correct places, finally outputting the formatted array to a text file.

$data = Import-Csv -Header 'account',"usage","sign","ConcatAddress" -Delimiter "`t" "c:\somefolder\messedupfile.txt"

$format = ' {0,-10:D10}{3,-36}{1:D9}{2}'
$output=foreach ($line in $data)
$format -f [Int64]$line.account,[Int64]$line.usage,$line.sign,$line.concataddress}
$output | Set-Content 'C:\somefolder\formated.txt'

Hey, see where I used “a” and sometimes ‘a’? turns out powershell doesn’t care which you use so long as the open and close quote style match.