function Format-TextJustified { param( [string[]]$Words, [int]$MaxWidth, [switch]$ExceptLastLine ) if ($Words.Count -eq 1) { $Words = $Words -split '\s+' } $preProcess = @() $row = @{ Letters = 0; Words = @() } foreach ($word in $Words) { if (($row.Words.Count -gt 0) -and ($row.Letters + $row.Words.Count + $word.Length -gt $MaxWidth)) { # adding this word to the array would make it cross the magic threshold # Add a new row to the array and start using that. $preProcess += $row $row = @{ Letters = 0; Words = @() } } $row.Words += $word $row.Letters += $word.Length } # push the final row $preProcess += $row $results = @() $rowCounter = 0 foreach ($row in $preProcess) { if ($row.Words.Count -eq 1 -or $rowCounter -eq $preProcess.Count) { $results += (($row.Words -join ' ') + "".PadRight($MaxWidth - $row.Letters - $row.Words.Count + 1)) continue } $rowWordCount = $row.Words.Count $countLessOne = $rowWordCount - 1 $spaces = $MaxWidth - $row.Letters $minSpaces = "".PadRight(([Math]::Floor($spaces/$countLessOne))) $addSpace = $spaces % $countLessOne $result = $row.Words[0] for($i = 1; $i -lt $rowWordCount; $i++) { $extraSpaces = "" if ($i -le $addSpace) { $extraSpaces = ' ' } $word = $row.Words[$i] $result += "$minSpaces$extraSpaces$word" } $results += $result } if ($ExceptLastLine) { $results[-1] = ($results[-1] -split '\s+') -join ' ' } return $results -join "`n" }