Aldo Aldo - 1 year ago 55
PowerShell Question

Powershell long text Indentation/padding

I'm trying to indent a long string in a write-host.
While it trivial to .PadLeft() or prepend spaces in writing a short string, the same isn't true for a long one, as as soon as the cursor is at the last column of the string, it will continue from column 0 of the next row, e.g.:

"{0}Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." -f $(" " * 5)


will show up as

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliq
ua.


but what if I want it to obtain:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore mag
na aliqua.


?

Is there a way to accomplish this?
many thanks guys!

Answer Source

You'll have to split the string up yourself based on the width of the console, and then pad the string and display:

$consoleWidth = $Host.UI.RawUI.BufferSize.Width
$desiredIndent = 5  # spaces
$chunkSize = $consoleWidth - $desiredIndent

$bigString = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '*10

[RegEx]::Matches($bigString, ".{$chunkSize}|.+").Groups.Value | ForEach-Object {
    ' '*$desiredIndent + $_
}