Format Strings
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 9 of 28.
The -f operator fills a format string. {0} is replaced by the first value after -f, {1} by the second, and so on:
"{0} scored {1} points" -f "Ivy", 87
"{0:N2} km" -f 5
"[{0,-6}][{1,5}]" -f "ab", 42Ivy scored 87 points
5.00 km
[ab ][ 42]After a colon comes the number format: N2 is a number with 2 decimals and a thousands separator, N0 a whole number, D3 a whole number padded to 3 digits (007), P0 a percent.
After a comma comes the width. A positive width pads on the left, so numbers line up on the right; a negative width pads on the right, so text lines up on the left. Width and format can go together: {1,8:N2}.
Challenge
EasyPrint a price list whose columns line up.
- Every row is a name in a column 8 characters wide, padded on the right, then a price in a column 8 characters wide, padded on the left, with 2 decimals.
- Print the header row with the words
ItemandPricein the same two columns. - Print the rows for
Coffee(3.5),Bagel(2.25) andJuice(12). - Print a last row with
Total:and the sum of the three prices, computed by the script.
Your script prints:
Item Price
Coffee 3.50
Bagel 2.25
Juice 12.00
Total: 17.75Try it yourself
$coffee = 3.5
$bagel = 2.25
$juice = 12
# Print the header, the three rows and the total
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check