PowerShell: Format String
💡 TIP: Operator names are case-insensitive.
-f (string format operator)
the string format operator syntax:
string -f args
use {0}
, {1}
, {2}
etc as placeholder in string.
(Microsoft calls this composite formatting)
"a {0} b {1}" -f 3, 4 # a 3 b 4 "a {1} b {0}" -f 3, 4 # a 4 b 3
Syntax for Placeholder
one of:
{index}
{index:formatSpec}
if you need alignment, use one of:
{index,alignment}
{index,alignment:formatSpec}
value meaning
- index is a integer, starting from 0.
- alignment is a integer. Means width. Positive means align right. Negative means align left.
- formatSpec is a short string indicating how to format it (e.g. Binary, hexadecimal, number of decimal places, with 3-digits grouping separator, etc.).
Format Code for Numbers
here are the code for the output format.
d
→ decimale
→ scientific notationf
→ fixed-pointg
→ general (either fixed-point format or scientific, whichever is shorter.)
b
→ binaryx
→ hexadecimal
c
→ currencyn
→ number with group separatorsp
→ percentr
→ roundtrip (a string representation of the exact number)
Format Code for Date Time
d
→ short dateD
→ long datet
→ short timeT
→ time with seconds
Escaping Braces
to include literal braces, use double braces.
"{{literal braces}} {0}" -f 3 # {literal braces} 3
Example. Output Decimal Numbers
# show 2 decimal places "{0:f2}" -f 12.345 # 12.35 # show 5 decimal places "{0:f5}" -f 12.345 # 12.34500 # show 2 decimal places, with grouping "{0:n2}" -f 123456789.123456789 # 123,456,789.12
Example. Output Integer
# show zero decimal places "{0:f0}" -f 12.345 # 12 # show zero decimal places, with grouping "{0:n0}" -f 1234567.1234567 # 1,234,567
Example. Output Hexadecimal
(input should be integer only)
"hexadecimal is {0:x}" -f 10 # hexadecimal is a
Example. Output Binary
(input should be integer only)
"binary is {0:b}" -f 10 # binary is 1010
Example. Output Currency
# by default, 2 decimal places "{0:c}" -f 12.3456 # $12.35 # output 4 decimal places "{0:c4}" -f 12.34 # $12.3400
Example. Pad 0 in Front
# pad with three 0 in front "this number {0:000}" -f 3 # this number 003 "this number {0:000}" -f 1234 # this number 1234
Example. Pad Space in Front
# pad space, total width 4 "pad space {0,4}" -f 123
Example. Format Date
"date is {0:d}" -f (Get-Date) # date is 9/10/2025 "date is {0:D}" -f (Get-Date) # date is Wednesday, September 10, 2025 "short time {0:t}" -f (Get-Date) # date is 10:39 AM "time with seconds {0:T}" -f (Get-Date) # date is 10:39:08 AM
PowerShell, string and regular expression
- PowerShell: String
- PowerShell: Single Quoted String
- PowerShell: Double Quoted String
- PowerShell: Here-String
- PowerShell: Escape Characters
- PowerShell: String Length
- PowerShell: Join String
- PowerShell: Split String
- PowerShell: Format String
- PowerShell: String Methods
- PowerShell: String Wildcards
- PowerShell: Regular Expression Operators
- PowerShell: Regex Result ($Matches)
- PowerShell: Regular Expression Syntax