0
0
PowerShellscripting~5 mins

-replace operator in PowerShell

Choose your learning style9 modes available
Introduction

The -replace operator helps you change parts of text easily. It finds a pattern and swaps it with new text.

You want to fix a typo in a text file.
You need to change all dates from one format to another.
You want to remove unwanted characters from a string.
You want to update words in a list of names.
You want to replace spaces with underscores in file names.
Syntax
PowerShell
'original text' -replace 'pattern', 'replacement'

The -replace operator uses regular expressions to find patterns.

It returns a new string with replacements; it does not change the original string.

Examples
This replaces the word 'world' with 'PowerShell'.
PowerShell
'hello world' -replace 'world', 'PowerShell'
This removes all non-digit characters from the phone number.
PowerShell
'123-456-7890' -replace '\D', ''
This changes commas and spaces to semicolons and spaces.
PowerShell
'apple, banana, cherry' -replace ', ', '; '
Sample Program

This script replaces 'cats' with 'birds' in the sentence.

PowerShell
$text = 'I love cats and dogs.'
$newText = $text -replace 'cats', 'birds'
Write-Output $newText
OutputSuccess
Important Notes

The -replace operator is case-insensitive by default.

To make it case-sensitive, use -creplace instead.

Remember, it works with patterns, so special characters need to be escaped.

Summary

-replace changes parts of text by matching patterns.

It uses regular expressions, so it can do simple or complex replacements.

It returns a new string and does not modify the original text.