In this episode of PoshBytes, we pit -replace against .Replace() in a battle of brains versus brawn. Regex wizardry versus the blunt hammer of literal text replacement. Learn when to wield the wand and when to swing the mallet in your PowerShell scripts!
This post is a companion for the video embedded below. Scroll down to see the code from the video.
Case sensitivity
Demonstrates case sensitivity in string replacement using both .Replace() and -replace operators.
"PowerShell".Replace('shell','boat')
"PowerShell" -replace 'shell','boat'
Shows the case sensitivity of the -creplace operator.
"PowerShell" -creplace 'shell','boat'
# Case sensitivity
Illustrates case sensitivity with word boundaries in replacement.
'cat category bobcat'.Replace('cat','dog')
'cat category bobcat' -replace '\bcat\b','dog'
Whole words vs partials
Replaces individual digits in a string with asterisks through multiple replacements versus a single pattern.
'Invoice #12345'.Replace('1','*').Replace('2','*').Replace('3','*').Replace('4','*').Replace('5','*')
'Invoice #12345' -replace '\d','*'
Multiple literals vs one pattern
Displays the replacement of multiple literals with single characters.
'red green blue'.Replace('red','r').Replace('green','g').Replace('blue','b')
'red green blue' -replace 'red|green|blue', { $_.Value[0] }
Transforms each word in a string to capitalize the first letter, applied to both English and Spanish characters.
'one two three' -replace '\b\w+\b',{ $_.Value.Substring(0,1).ToUpper() + $_.Value.Substring(1) }
'niño año café' -replace '\b\p{L}+\b',{ $_.Value.Substring(0,1).ToUpper() + $_.Value.Substring(1) }
Regex Returns Values
Shows how to replace the ‘+’ character with ‘ plus ‘ in a string, using both .Replace() and -replace.
'1+1=2'.Replace('+',' plus ')
'1+1=2' -replace '+',' plus '
Escapes the ‘+’ character using regex.
[regex]::Escape('+')
Replaces the ‘+’ character with ‘ plus ‘ using regex.
'1+1=2' -replace '\+',' plus '
Special characters
Formats a date string from ‘YYYY-MM-DD’ to ‘MM/DD/YYYY’ using regex replacement.
'2025-10-25' -replace '(\d{4})-(\d{2})-(\d{2})','$2/$3/$1'
Formats the date string to ‘DD/MM/YYYY’.
'2025-10-25' -replace '(\d{4})-(\d{2})-(\d{2})','$3/$2/$1'