normal CSV file to a fixed record-size text file
has seen utility written in powershell in public repository take csv file , write out fixed length record text file each field of data in csv occupy same columns in each record of text file?
i'm imagining pre-pass find widths needed each column , pass on csv file write fields right-justified in width each column.
for example,
just noticed output format-table left-justified, , mentioned right-. didn't see way change this, wound having write function pretty described.
function convertto-tablestring { [cmdletbinding()] param ( [parameter(mandatory=$true,valuefrompipeline=$true)] [system.object[]] $inputobject ) begin { $columnwidths = new-object 'system.collections.generic.dictionary[[system.string],[system.int32]]' $objectlist = new-object 'system.collections.generic.list[system.object]' } process { foreach ($object in $inputobject) { $objectlist.add($object) foreach ($prop in ($object | get-member -membertype noteproperty)) { $propname = $prop.name $length = $object.$propname.tostring().length if ($columnwidths.containskey($propname)) { if ($length -gt $columnwidths[$propname]) { $columnwidths[$propname] = $length } } else { $columnwidths.add($propname, $length) } } } } end { $sb = new-object system.text.stringbuilder foreach ($object in $objectlist) { $sb.clear() | out-null foreach ($property in $columnwidths.keys) { if ($sb.length -gt 0) { $sb.append(" ") | out-null } $sb.appendformat("{0,$($columnwidths[$property])}", $object.$property) | out-null } $sb.tostring() | write-output } } } $csvpath = '.\test.csv' $outputpath = '.\test.txt' # determine number of fields in csv , make dummy header array real import. # note : fail if csv file contains single record, writing # way faster writing string-based version handles proper quoting / # delimeter / comment rules of csv file. $csvdata = import-csv -path $csvpath if (!$csvdata) { return } $header = @() $props = $csvdata | get-member -membertype noteproperty ($i = 0; $i -lt $props.count; $i++) { $header += $i.tostring('x') } # re-import csv our fake headers, , use convertto-tablestring generate # desired text output. ridiculously huge width value passed out-file # don't truncate data (unless line might have more 2 billion or # characters) import-csv -path $csvpath -header $header | convertto-tablestring | out-file -filepath $outputpath -width ([system.int32]::maxvalue)
Windows Server > Windows PowerShell
Comments
Post a Comment