PowerShell ABC's - F is for Format Operator

Welcome to this addition of the PowerShell ABC's where you'll find 26 posts detailing a component of the PowerShell scripting language, one letter at a time.  Today's letter is the letter "F".  For "F" I've picked the word that relates to how you can make nice and pretty output.  Today's word is the Format operator (-f).

Most often, PowerShell's build in output formatting is good enough for your needs.  But, there will always be those times when you want a more fine grained control over the formatting of your output.  You may also want to format strings in a specific way.  Enter the format operator "-f".

The format operator -f is a binary operator that takes a format string as it's left operand and an array of values to format as it's right operand.

PS> "{2} {0}" -f "there", "ignore", "hi"

hi there

In the format string, the values enclosed in braces correspond to the index of the element on the right operand array.  Along with reordering, you can also control how the array values are laid out.  It behaves very similar to pythons "%" operator.  The format operator is a shorthand for calling the .NET Format method in the System.String class.

The basic format for the index specifiers is

([,][:])

This is best illustrated with a couple of examples.  Here is a table taken from PowerShell in Action by Bruce Payette:


OperatorExampleResultsDescription

{0}Display a particular element"{0} {1}" -f "a", "b"a b
{0:x}Display a number in Hexadecimal"0x{0:x}" -f 1813420x2c45e
{0:X}Display a number in Hexadecimal uppercase"0x{0:X}" -f 1813420x2C45E
{0:dn}Display a decimal number left justified, padded with zeros"{0:d8}" -f 300000003
{0:p}Display a number as a percentage"{0:p}" -f .12312.30 %
{0:c}Display a number as currency"{0:c}" -f  12.34$12.34
{0,n}Display with field width n, left aligned"|{0,5}|" -f "hi"|   hi|
{0,-n}Display with field width n, right aligned"|{0,-5}| -f "hi"|hi   |
{0:hh}
{0:mm}
Display the hours and minutes from a date time value"{0:hh}:{0:mm}" -f (Get-Date)01:34
{0:C}Display using the currency symbol for the current culture"|{0,10:C}|" -f 12.3|    $12.40|

There are a lot more things you can do with formatting than are illustrated in this table.  For more information, check out the Formatting Overview on MSDN.

Published Dec 19, 2008
Version 1.0

Was this article helpful?