0
0
PowerShellscripting~5 mins

Formatting with -f operator in PowerShell

Choose your learning style9 modes available
Introduction
The -f operator helps you create neat and readable text by inserting values into a string in a clear way.
When you want to show a message with numbers or names in a sentence.
When you need to line up columns of data for easy reading.
When you want to control how many decimal places a number shows.
When you want to add leading zeros or spaces to numbers or text.
When you want to build a string with different types of data combined.
Syntax
PowerShell
'format string {0} {1}' -f value1, value2
The numbers in curly braces {0}, {1}, etc. are placeholders for values.
Values after -f replace placeholders in order, starting at 0.
Examples
Inserts 'Alice' into the placeholder {0}.
PowerShell
'Hello, {0}!' -f 'Alice'
Uses the first value twice and the second value once.
PowerShell
'{0} + {0} = {1}' -f 2, 4
Formats number 7 with leading zeros to 4 digits: 0007.
PowerShell
'Number: {0:D4}' -f 7
Formats number as currency with 2 decimals, e.g., $12.50.
PowerShell
'Price: {0:C2}' -f 12.5
Sample Program
This script creates a message with a name, age, and balance formatted as currency with 2 decimals.
PowerShell
$name = 'Bob'
$age = 30
$balance = 1234.5

$message = 'Name: {0}, Age: {1}, Balance: {2:C2}' -f $name, $age, $balance
Write-Output $message
OutputSuccess
Important Notes
You can reuse the same placeholder number multiple times in the format string.
Formatting codes like D4 or C2 control how numbers appear (digits, currency, decimals).
If you have more placeholders than values, PowerShell will show an error.
Summary
The -f operator inserts values into a string using placeholders like {0}, {1}.
You can format numbers and text for better readability.
It helps make output clear and professional-looking.