Undo-TextWrapping.psm1
#.SYNOPSIS # Takes one or more lines of text that were produced by a text-wrapping algorithm # and attempts to 'unwrap' them so that the line breaks that were added are removed. # #.DESCRIPTION # Unwrapping text is an error-prone process, because it is impossible to know for sure # whether or not a hard line break was intentional or added as a result of word-wrapping. # This function makes several assumptions about wrapped text. For example, if there are # spaces at the end of a line and the following line is not blank, it is assumed that the # line was wrapped. If there is a space on a blank line, it is assumed that the line # break is intentional and will not be unwrapped. # #.EXAMPLE # Get-Help ForEach-Object | Select -Expand Description | Undo-TextWrapping # function Undo-TextWrapping { [CmdletBinding()] [OutputType([String])] param ( # The lines of text to unwrap, which may be supplied # on the pipeline. [Alias('Text')] [AllowEmptyString()] [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$InputString ) begin { $Lines = @() $CurrentLine = "" } process { foreach ($Line in @($InputString -split '[\r\n|\r|\n]')) { # Skip this shit if ($Line -eq $Null) { continue } switch -regex ($Line) { # Special circumstances where we believe this to # definitely be a new line. (ie. list patterns, # space(s) at beginning of line, etc) '^(\s|\d+[\.\)\]]\s|\-\s)' { # Commit the current line if ($CurrentLine) { $Lines += $CurrentLine.TrimEnd() } $CurrentLine = $Line break } # Line is not blank '\S' { $CurrentLine += $Line.TrimEnd() + ' ' break } # Blank or contains only spaces '^\s*$' { # Commit the current line if ($CurrentLine) { $Lines += $CurrentLine.TrimEnd() } $CurrentLine = '' break } } } } end { # If we have anything left over... if ($CurrentLine) { $Lines += $CurrentLine.TrimEnd() } for ($i=0; $i -lt $Lines.Count; $i++) { Write-Verbose $Lines[$i] } $Lines } } |