0
0
PowerShellscripting~5 mins

Formatting with -f operator in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the -f operator do in PowerShell?
The -f operator formats strings by replacing placeholders with values, similar to filling blanks in a sentence.
Click to reveal answer
beginner
How do you use the -f operator to insert a variable into a string?
Use curly braces with numbers as placeholders in the string, then after -f list the variables in order. Example: "Hello, {0}!" -f $name
Click to reveal answer
beginner
What will this code output? `"{0} + {1} = {2}" -f 2, 3, (2+3)`
It outputs: "2 + 3 = 5" because {0} is 2, {1} is 3, and {2} is the sum 5.
Click to reveal answer
intermediate
Can you format numbers with decimals using -f? How?
Yes, by adding format specifiers inside the placeholder. Example: "{0:N2}" -f 3.14159 outputs "3.14" (2 decimals).
Click to reveal answer
intermediate
What happens if you use a placeholder index that does not have a matching argument in -f?
PowerShell throws an error because it expects a value for every placeholder index used in the string.
Click to reveal answer
What does the placeholder {0} represent in a string using -f?
AThe first argument after -f
BThe last argument after -f
CA variable named 0
DA comment in the string
How would you format the number 1234.5678 to show only two decimals using -f?
A"{0:2}" -f 1234.5678
B"{0:F}" -f 1234.5678
C"{0:N2}" -f 1234.5678
D"{0:D2}" -f 1234.5678
What will this output? `"{1} and {0}" -f "apple", "banana"`
Aapple and banana
Bbanana and apple
C{1} and {0}
DError
If you forget to provide enough arguments for placeholders, what happens?
APowerShell fills missing with empty strings
BPowerShell repeats last argument
CPowerShell ignores extra placeholders
DPowerShell throws an error
Which of these is a correct use of -f to format a greeting with a name variable?
A"Hello, {0}!" -f $name
B"Hello, $name!" -f
C"Hello, {name}!" -f $name
D"Hello, {1}!" -f $name
Explain how the -f operator works in PowerShell and give a simple example.
Think of filling blanks in a sentence with values.
You got /3 concepts.
    Describe how to format a number to two decimal places using the -f operator.
    Look inside the curly braces for formatting instructions.
    You got /3 concepts.