Posts RSS Comments RSS 253 Posts and 411 Comments till now

The Power of -f. The Format Operator

This is from a NG post discussing the -f Operator… I thought it was a pretty good description. Compliments to Kiron.

Q: What is the -f operator

A: PowerShell’s Format Operator ‘-f’ is equivalent to .Net’s Composite
Formatting. The syntax is:
{index[,alignment][:formatString]} -f listOfValues

Composite Formatting

Quoting from about_operator:
Format Operator “-f”
The format operator provides support for formatting strings via the .NET
string object format method. On the left hand side of the operator is the
format string and on the right hand of the operator is the collection of
objects to be formatted.
The following example shows some of the capabilities of the format operator.
PS> “{0} {1,-10} {2:N}” -f 1,”hello”,[math]::pi
1 hello 3.14

Some samples:

# the ‘|’ is for demonstrating the alignment
"{0:(###) ###-####}" -f 2224445555 # phone number
"{0:hh:mm:ss tt}" -f (get-date) # time, 12 hour format
"{0:HH:mm:ss}" -f (get-date) # time, 24 hour format
"{0:p4}" -f (1/3) # percent with four decimal places
"{0:c2}" -f (1724.87 * 12) # currency with two decimal places
"|{0,22:c2}|" -f (1724.87 * 12) # right aligned currency with two decimal places
"|{0,-22:n2}|" -f (13/57) # left aligned number with two decimal places
"{0:MM dd yy}" -f (get-date) # date, custom short format
"{0:MMMM yyyy}" -f (get-date) # date, ‘month year’ format
0..15 | % {"{0:0##}" -f $_} # filled number format
0..15 | % {"|{0,33}|" -f "Number $_"} # right aligned string
0..15 | % {"|{0,-33}|" -f "Number $_"} # left aligned string
0..15 | % {"|{0,33}|  |{0,-33}|" -f "Number $_"} # right & left aligned string

Suggested Reading.

Standard Numeric Format Strings

Custom Numeric Format Strings

Standard DateTime Format Strings

Custom DateTime Format Strings

Enumeration Format Strings

Check out this blog from the PowerShell Team

3 Responses to “The Power of -f. The Format Operator”

  1. on 15 Dec 2007 at 7:41 amIdetrorce

    very interesting, but I don’t agree with you

  2. on 15 Dec 2007 at 10:44 amBrandon

    I appreciate the feedback, but what exactly don’t you agree with?

  3. […] are a few other ones out there as […]

Trackback this post | Feed on Comments to this post

Leave a Reply

You must be logged in to post a comment.