Nicely Wrapping a Line of text to STDOUT
In case you didn't know, $host gives data about the scripting host, including the window containing the script's output. This in turn gives us the width of the window:
$Host.UI.RawUI.WindowSize.Width
From there, we can
function Break-Line {
# synopsis::
# [-help]
#
# Description::
# Inserts linefeeds into strings read from STDIN so they wrap nicely
# for a given PowerShell window's screen geometry
#
# Usage::
# $data | Break-Line
param (
[switch]$help
);
if ($help) { return (Get-FunctionHelp -name $MyInvocation.MyCommand.Name); }
$width = $Host.UI.RawUI.WindowSize.Width - 1;
$input | % {
$_ = $_ -replace "`t", " ";
foreach ($line in $_.split("`n")) {
$line = $line -replace "\s*$";
$indent = $line -replace "(^\s*).*", '$1';
$line = $line -replace "^\s*";
while ($line.length -gt ($width - $indent.length)) {
$splitPoint = $width - $indent.length;
$buffer = $line.SubString(0, $splitPoint);
$offset = $buffer.lastIndexOf(" ")
if (($offset -ne -1) -and ($offet -ne ($buffer.length -1))) {
$splitPoint = $offset;
$buffer = $line.SubString(0, $splitPoint);
}
$line = $line.SubString($splitPoint, ($line.length - $splitPoint)) -replace "^\s*";
"$indent$buffer";
}
"$indent$line";
}
}
}