Functions/Split-DryString.ps1

Function Split-DryString {
    Param (
        [Parameter(Mandatory,HelpMessage="The string to split into chunks of a certain maximum length")]
        [ValidateNotNullOrEmpty()]
        [String]
        $String,

        [Parameter(Mandatory,HelpMessage="The function will split `$String into an array of strings, or
        chunks, of maximum length `$Length. They may be shorter - see description of paramameter
        `$WhiteSpaceAtEndChars below"
)]
        [ValidateScript({"$_ -gt 1"})]
        [Int]
        $Length,

        [Parameter(HelpMessage="In order not to split a sentence in the middle of a word, the function
        will search the last 10 (or, the number of `$WhiteSpaceAtEndChars) chars, of each chunk, for a
        whitespace. If a whitespace is found within those chars, it will split at the whitespace instead
        of exactly at `$Length"
)]
        [Int]
        $WhiteSpaceAtEndChars = 10
    )

    $Chunks = @()
    $i = 0

    # Replace tabs with whitespace
    $String = $String.Replace("`t"," ")

    While ($i -le ($String.length-$Length)){
        $Chunk = $String.Substring($i,$Length)
        # Search for the last whitespace in the $WhiteSpaceAtEndChars number of
        # characters at the end of each chunk. But only if all of the following
        # conditions are met:
        # - the chunk is of the full length
        # - the charachter following the chunk is not a whitespace
        # - the last character of the chunk is not a whitespace
        # If such a whitespace is found, we split at that instead
        If ($String.Length -gt ($i+$Chunk.Length+1) ) {
            If ( ($Chunk.Length -eq $Length) -and ( $String.Substring($i+$Chunk.Length,1) -ne ' ') -and ( $Chunk.Substring($Chunk.Length-1) -ne ' ') ) {
                $LastWhiteSpace = ($Chunk.Substring($Chunk.Length-$WhiteSpaceAtEndChars)).LastIndexOf(' ')
                If ($LastWhiteSpace -ge 0) {
                    $cutindex = $WhiteSpaceAtEndChars - ($LastWhiteSpace+1)
                    $Chunks += ($String.Substring($i,$Length-$cutindex)).Trim()
                    $i += $Length-$cutindex
                }
                Else {
                    # No Whitespace found
                    $Chunks += ($String.Substring($i,$Length)).Trim()
                    $i += $Length
                }
            }
            Else {
                # Just add to chunks and add $Length to $i
                $Chunks += ($String.Substring($i,$Length)).Trim()
                $i += $Length
            }
        }
        Else {
            $Chunks += ($String.Substring($i,$Length)).Trim()
            $i += $Length
        }
    }
    If (($String.Substring($i)).Trim() -ne '') {
        $Chunks += $String.Substring($i)
    }
    $Chunks
}