fbpx Place Formatted Information in a String in Windows PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Place Formatted Information in a String in Windows PowerShell

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say