0
0
PowerShellscripting~5 mins

-replace operator in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the -replace operator do in PowerShell?
The -replace operator in PowerShell replaces text in a string using a pattern. It searches for a pattern and replaces it with new text.
Click to reveal answer
beginner
How do you replace all occurrences of 'cat' with 'dog' in the string 'cat and cat' using -replace?
Use 'cat and cat' -replace 'cat', 'dog'. This changes both 'cat' words to 'dog', resulting in 'dog and dog'.
Click to reveal answer
intermediate
What kind of pattern does the -replace operator use to find text?
It uses regular expressions (regex) to find patterns in text. This means you can use special symbols to match complex text patterns.
Click to reveal answer
beginner
True or False: The -replace operator changes the original string variable directly.
False. Strings in PowerShell are immutable, so -replace returns a new string with changes. You must assign it to a variable if you want to keep it.
Click to reveal answer
advanced
How can you replace only the first occurrence of a pattern using -replace?
By default, -replace replaces all matches. To replace only the first, you can use the .NET method [regex]::Replace() with a count parameter.
Click to reveal answer
What does 'hello world' -replace 'world', 'PowerShell' output?
APowerShell world
Bhello world
Chello PowerShell
Dhello
Which pattern matching method does -replace use?
ASimple text matching only
BExact match only
CWildcard matching
DRegular expressions
If you want to replace all digits in a string with '#' using -replace, which pattern should you use?
A'\d'
B'[a-z]'
C'\w'
D'\s'
What happens if you run $text = 'apple'; $text -replace 'a', 'o' without assigning the result?
ANothing changes in $text; output shows 'opple'
BThe variable $text changes to 'opple'
CAn error occurs
DThe original string is deleted
How do you replace only the first match of a pattern in PowerShell?
AUse <code>-replace</code> with a special flag
BUse <code>[regex]::Replace()</code> with a count parameter
CUse <code>-replace</code> twice
DIt is not possible
Explain how the -replace operator works in PowerShell and give a simple example.
Think about how you change words in a sentence.
You got /4 concepts.
    Describe how you would replace only the first occurrence of a pattern in a string using PowerShell.
    PowerShell's -replace replaces all by default.
    You got /3 concepts.