Problem
You want to place formatted information (such as rightaligned text or numbers rounded to a specific number of decimal places) in a string.
Solution
Use PowerShell’s formatting operator to place formatted information inside a string.
PS >$formatString = "{0,8:D4} {1:C}`n" PS >$report = "Quantity Price`n" PS >$report += "`n" PS >$report += $formatString f 50,2.5677 PS >$report += $formatString f 3,9 PS >$report Quantity Price
0050 $2.57 0003 $9.00
Discussion
PowerShell’s string formatting operator (f) uses the same string formatting rules as the String.Format() method in the .NET Framework. It takes a format string on its left side, and the items you want to format on its right side.
In the solution, you format two numbers: a quantity and a price. The first number ({0}) represents the quantity and is rightaligned in a box of 8 characters (,8). It is formatted as a decimal number with 4 digits (:D4). The second number ({1}) represents the price, which you format as currency (:C).
For a detailed explanation of PowerShell’s formatting operator, see “Simple Opera tors”, PowerShell Language and Environment.
Although primarily used to control the layout of information, the stringformatting operator is also a readable replacement for what is normally accomplished with string concatenation:
PS >$number1 = 10 PS >$number2 = 32 PS >"$number2 divided by $number1 is " + $number2 / $number1 32 divided by 10 is 3.2
The string formatting operator makes this much easier to read:
PS >"{0} divided by {1} is {2}" f $number2, $number1, ($number2 / $number1) 32 divided by 10 is 3.2
In addition to the string formatting operator, PowerShell provides three formatting commands (FormatTable, FormatWide, and FormatList) that lets you to easily gen erate formatted reports.