There are two very simple ways to replace text within a string in Powershell.
First, let's look at using the replace function.
Using the replace() function
You can replace part of a string using the replace function:
$str = "Hello world!" $str.replace("world", "Mars")
There are two things to note here:
- Parameters are case sensitive
- The function will replace every instance of the string it finds
For instance, if we attempt the same with a more repetitive string:
$str = "Hello, hello, hello world!" $str.replace("hello", "ello")
Hello, ello, ello world!
Note that two out of three instances were replaced. The first instance of "hello" however, was capitalized, and therefore ignored (there's a solution to this in the operator example below).
Using the -replace operator
Alternatively, we could use the -replace operator:
$str = "Hello world!" $str -replace "world", "Earth"
Whilst this still changes every instance of the substring that it finds, this time the parameter is case insensitive:
$str = "Hello, hello, hello world!" $str -replace "hello", "ello"
ello, ello, ello world!
One of the advantages of using the operator over the function, is that you can supply regular expressions to the first parameter of the replace operator,
For instance, if we wanted to replace all instances of the words "world", "earth", and "mars", we could either perform the replace three times, or simply use the OR RegEx operator: |
$str = "Hello world!" $str -replace "world|earth|mars", "unspecified planetary body"
Hello unspecified planetary body!