Input file is a fixed-width txt file. My client normally opens it in Excel and manually specifies the column breaks. I\'m hoping to replace certain blank spaces with a comma
I would think this comes up a lot. Here's an example that actually goes overboard and turns the fixed width file into objects. Then it's simple to export that to a csv. This should work for converting legacy commands like netstat as well.
$cols = 0,19,38,59,81,97,120,123 # fake extra column at the end, assumes all rows are that wide, padded with spaces
$colsfile = 'columns.txt'
$csvfile = 'cust.csv'
$firstline = get-content $colsfile | select -first 1
$headers = for ($i = 0; $i -lt $cols.count - 1; $i++) {
$firstline.substring($cols[$i], $cols[$i+1]-$cols[$i]).trim()
}
# string Substring(int startIndex, int length)
Get-Content $colsfile | select -skip 1 | ForEach {
$hash = [ordered]@{}
for ($i = 0; $i -lt $headers.length; $i++) {
$value = $_.substring($cols[$i], $cols[$i+1]-$cols[$i]).trim()
$hash += @{$headers[$i] = $value}
}
[pscustomobject]$hash
} | export-csv $csvfile