-f Format operator

Format a string expression.

Place {0} {1} etc. into the string as placemarkers where you want the variables to appear, immediately follow the string with the -f operator and then lastly, the list of comma separated variables which will be used to populate the placemarkers.

Get-ChildItem c:\docs | ForEach-Object {'Filename: {0} Created: {1}' -f $_.fullname,$_.creationtime}

Syntax:

"{I,A:FS} {I,A:FS} {I,A:FS}.." -f "string0", "string1", "string2"...

Key:

I = Index of the item to display, 0=string0, 1=string1 etc.

A = Alignment.
A positive number will right align n characters.
A negative number will left align n characters.
so {2,-25} will allocate 25 characters of horizontal space on the line, even if the string is only 1 character long.

FS = an optional format string that acts on the item depending on its type.
Valid format strings (not case sensitive):

:c Currency format
:e Scientific (exp) notation
:f Fixed point
:f5 = fix to 5 places
:g Most compact format, fixed or sci
:g5 = 5 significant digits
:n include culture separator for thousands 1,000.00
:p percentage
:r reversible precision
:x Hex format
:hh
:mm
:ss
Convert a DateTime to a 2 digit Hour/minute/second
"{0:hh:0:mm}"
:ddd Convert a DateTime to Day of the Week

A full list of Date Formats

The format string can be surrounded by either single or double quotes.
Static text may be included before or in-between the -f {format strings.}

Examples:

PS C:\> "{1,10} {0,10} {2,10:x}" -f "First", "Second", 255
    Second     First        FF

PS C:\> "{0} {1,-10} {2:N}" -f 1, "hello",[math]::pi
1 hello 3.14

“I skate to where the puck is going to be, not where it has been” ~ Wayne Gretsky

Related:

PowerShell Operators - Format strings and arrays
Variables - PowerShell Variables and basic Mathematical operators (+ - = /)
Pipelines - Pass objects down the pipeline


© Copyright SS64.com 1999-2014
Some rights reserved