Text alignment

Composite formatting (text alignment).

PowerShell composite formatting among other things, is a way of writing text to the console which we may not be able to achieve with the usual ‘Write-Host’ or ‘Write-Output’ cmdlets. For example, we may wish to write some text to the console aligned to the left or right (left or right-justified).

This article shows how this can be done.

The .NET composite (PowerShell) formatting feature takes a list of objects and a composite format string as input. So if we wish to align text to the left or right, this is the sort of actions we can take. Each format item takes the following form and consists of the following components:

{index[,alignment][:formatString]}

The matching curley braces ({ and }) are required.

Left-aligned – if negative
Right-aligned – if positive

We can see all of those components work together with the a money example:

$money = 6703106;
Write-Host ('{0,-15:C}' -f $money);

Which should look like:

       £6,703,106.00

In the example below, the work ‘Hello’ is left-aligned because the alignment component is negative. The word ‘World’ is right-aligned because the alignment component is positive.

Write-Host ("[{0,-10}] [{1,10}]" -f 'Hello', 'World');
[Hello     ] [     World]

See also

Composite formatting
https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting?redirectedfrom=MSDN

Use PowerShell to Format Strings with Composite Formatting
https://devblogs.microsoft.com/scripting/use-powershell-to-format-strings-with-composite-formatting/

This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a comment