Skip to content

Instantly share code, notes, and snippets.

@theunrepentantgeek
Created April 26, 2016 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theunrepentantgeek/e768a6fd5af45712554440aca74d8706 to your computer and use it in GitHub Desktop.
Save theunrepentantgeek/e768a6fd5af45712554440aca74d8706 to your computer and use it in GitHub Desktop.
Example wrap-string function
# Word wrap function, return word wrapped version of passed string
function wrap-string($str, $length)
{
if ($str.length -lt $length)
{
return $str
}
# Holds the final version of $str with newlines
$strWithNewLines = ""
# current line, never contains more than screen width
$curLine = 0
# Loop over the words and write a line out just short of window size
foreach ($word in $str.Split(" "))
{
# Lets see if adding a word makes our string longer then window width
if (($curLine + 1 + $word.length) -gt $length)
{
# With the new word we've gone over width
# append newline before we append new word
$strWithNewLines += "`r`n" + $word
# Reset current line
$curLine = $word.length
}
else
{
# Append word to current line and final str
if ($curLine -gt 0)
{
$strWithNewLines += " "
}
$curLine += $word.Length + 1
$strWithNewLines += $word
}
}
# return our word wrapped string
return $strWithNewLines
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment