PowerShell Script to Replace Character in String
-replace like this: $newString = $oldString -replace 'oldChar', 'newChar' to replace characters in a string.Examples
How to Think About It
-replace that does this in one step.Algorithm
Code
$oldString = "hello world" $newString = $oldString -replace ' ', '_' Write-Output $newString
Dry Run
Let's trace replacing space with underscore in 'hello world' through the code
Original string
$oldString = "hello world"
Replace space with underscore
$newString = $oldString -replace ' ', '_' # Result: 'hello_world'
Output result
Write-Output $newString # Prints 'hello_world'
| Step | String Value |
|---|---|
| Initial | hello world |
| After replace | hello_world |
Why This Works
Step 1: Use of -replace operator
The -replace operator in PowerShell searches the string for the specified old character and replaces all its occurrences with the new character.
Step 2: Assigning the result
The result of the replacement is stored in a new variable so the original string remains unchanged unless reassigned.
Step 3: Outputting the new string
Using Write-Output prints the modified string to the console for verification.
Alternative Approaches
$oldString = "hello world" $newString = $oldString.Replace(' ', '_') Write-Output $newString
$oldString = "Hello World" $newString = $oldString -creplace ' ', '_' Write-Output $newString
Complexity: O(n) time, O(n) space
Time Complexity
The operation scans each character in the string once, so time grows linearly with string length.
Space Complexity
A new string is created for the result, so space also grows linearly with the input size.
Which Approach is Fastest?
The .Replace() method is generally faster for simple replacements without regex, while -replace is more flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| -replace operator | O(n) | O(n) | Flexible replacements with regex |
| .Replace() method | O(n) | O(n) | Simple, case-sensitive replacements |
| -creplace operator | O(n) | O(n) | Case-sensitive regex replacements |
-replace for simple character replacements and regex support in PowerShell.-replace uses regex, so special characters need escaping.