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?✗ Incorrect
The
-replace operator replaces 'world' with 'PowerShell', so the output is 'hello PowerShell'.Which pattern matching method does
-replace use?✗ Incorrect
-replace uses regular expressions, allowing complex pattern matching.If you want to replace all digits in a string with '#' using
-replace, which pattern should you use?✗ Incorrect
'\d' matches any digit in regex, so it replaces all digits.
What happens if you run
$text = 'apple'; $text -replace 'a', 'o' without assigning the result?✗ Incorrect
Strings are immutable;
-replace returns a new string but does not change $text unless assigned.How do you replace only the first match of a pattern in PowerShell?
✗ Incorrect
The .NET
Regex.Replace() method allows limiting replacements, unlike -replace.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.