Table of Contents

When using -F format Operator in PowerShell, in the first view it seems like a puzzle but after working with it gets simple.

-F format operator is basically a .NET based.

Why we need to use the -F format operator? 

Yes we have few cmdlets by using them we can format the output, but by using -F format operator we can do more than that.

SYNTAX

The syntax for -F format operator is

{<index>[,<alignment>][:<formatString>]}

Format Strings Description
C Currency
X Display Number in Hexa Decimal
p Display Number as Percentage
n Display with width n to left side
-n Display with width -n to right side
dn Display Numbers Padded by 0 by n times
# Digit placeholder,
, Thousand separator
\ Escape Character
:ddd Day of Week
:dd Day of Month
:dddd Full name of Day of Week
:hh Hour
:HH Hour in 24 Hour format
:mm Minutes
:SS Seconds
:MM Month in Number
:MMMM Name of the Month
:yy Year in short
:yyyy Full year

In -F format operator we provide the strings and numbers in the right hand side and stantax for -F in left hand side.

Position

In below examples we are just querying the first number in our right hand side. The first number is 1,

"{0}" -f 1,2,3,4,5


Ok now let's add some space in our first number.

"{0,10}" -f 1,2,3,4,5

You can see that the Position of "1" is moved to little bit on right hand side.

clip_image002

  • :c or :C | Currency

"{0:C}" -f 200,99,765

You can see that now the output is in currency.

clip_image003

Let's choose the second number

"{1:C}" -f 200,99,765

clip_image004

  • :x or :X | Hexa Decimal

"{0:x}" -f 909887

It Converted the Number 909887 to hexadecimal value.

clip_image005

  • :p | Percentage

"{0:p}" -f .703

Output is in Percentage.

clip_image006

  • :dn | Padded 0

"{0:d7}" -f 9

We specified to add 7 zeros but it added 6 , actually it added 7 and the last 0 replaced by the decimal number.

clip_image007

  • # | Digit Place Holder

"{0:###-##-##}" -f 8976203

When we use # in format operator the # are replaced by the digits.

clip_image008

  • Date and Time Formater

"{0:ddd}" -f (get-date)

"{0:dd}" -f (get-date)

"{0:dddd}" -f (get-date)

"{0:hh}" -f (get-date)

"{0:mm}" -f (get-date)

"{0:MM}" -f (get-date)

"{0:MMMM}" -f (get-date)

"{0:yy}" -f (get-date)

"{0:yyyy}" -f (get-date)

clip_image009

  • ,| Thousand separator

"{0:#,#}" -f 100980243

clip_image001

  • Practice Example
$pro = Get-Process
 
foreach ($a in $pro) {
 
"{0,20} {1,40}" -f $a.ProcessName , $a.vm
 
}

Try the above script and the output should be like this .

clip_image001

Useful Links

http://msdn.microsoft.com/en-us/library/26etazsy.aspx