Place Formatted Information in a String

1. Problem

You want to place formatted information (such as right-aligned text or numbers rounded to a specific number of decimal places) in a string.

2. 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



3. 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 right-aligned 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 Operators” in Appendix A, PowerShell Language and Environment. For a detailed list of the formatting rules, see Appendix H, .NET String Formatting.

Although primarily used to control the layout of information, the string-formatting 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:

Code View: Scroll / Show All

        PS >"{0} divided by {1} is {2}" -f $number2, $number1, ($number2 / $number1)
        32 divided by 10 is 3.2
Tags: , , , , , ,