Skip to content

Instantly share code, notes, and snippets.

@peruihkxt
Created May 7, 2019 16:19
Show Gist options
  • Save peruihkxt/7da728d02bae59c26674f60723ffee11 to your computer and use it in GitHub Desktop.
Save peruihkxt/7da728d02bae59c26674f60723ffee11 to your computer and use it in GitHub Desktop.
function ConvertFrom-FixedWidth($strings) {
# The first column is the header. We assume that columns are separated by at least two spaces.
$headerRegex = [regex] "\w+\s{2,}"
$columns = $headerRegex.Matches($strings[0]) | ForEach-Object { [pscustomobject]@{
Name = $_.Value.Trim()
Start = $_.Index
Length = $_.Length
} }
$values = @()
for ($i = 1; $i -lt $strings.Count; $i++) {
$s = $strings[$i]
if ($s.Length -ne 0) {
$value = @{ }
foreach ($column in $columns) {
if($s.Length -lt $column.Start + $column.Length){
break
}
$value."$($column.Name)" = $s.Substring($column.Start, $column.Length).Trim()
}
$values += [pscustomobject]$value
}
}
return $values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment