PowerShell offers a couple different methods for formatting text making it easy to get the output you want. The most commonly used methods are the format operator or using composite formatting. This article will discuss both of these methods and provide some examples.
Format Operator (-F)
#
# Define some variables that will go into our string
#
$name = "John Doe"
$job = "Accountant"
#
# Insert the variables into the string
#
"Employee: {0}, Occupation: {1}" -f $name,$job
[Output]
Employee: John Doe, Occupation: Accountant
Error formatting a string: Index (zero based) must be greater than or equal to zero and less
than the size of the argument list..
Composite Formatting
#
# Define some variables that will go into our string
#
$name = "John Doe"
$job = "Accountant"
[String]::Format("Employee: {0}, Occupation: {1}",$name,$job)
[Console]::WriteLine("His name is {0} and he is an {1}.",$name,$job)
[Output]
Employee: John Doe, Occupation: Accountant
His name is John Doe and he is an Accountant.
$date = Get-Date
$number = 12.99
#
# Write the Date in the format yyyy-MM-dd
#
"Today is: {0:yyyy-MM-dd}" -f $date
#
# Write a number as currency
#
[String]::Format("Amount is: {0:C}",$number)
[Output]
Today is: 2013-12-28
Amount is: $12.99