PowerShell replace operator uses the Regular Expression (regex) for pattern matching. To replace text in a string with a wildcard, we can do it using a regex in PowerShell replace operator.
In this article, we will discuss how to use replace with wild card characters and regex expressions in PowerShell replace operator.
Replace All Text with WildCard in PowerShell
To find all text in a string with a start string, use the PowerShell replace operator to find the text using the wildcard and replace them with a new string.
Let’s say, you have a string $str that contains the string “Assembly Version=188.8.131.52“
You want to replace all text that starts after the string Version= with a new string Version=184.108.40.206
$str = "Assembly Version=220.127.116.11" $str -replace 'Version=.*?.*','Version=18.104.22.168'
In the above PowerShell script, the $str contains the string.
We have used PowerShell replace operator over the string to find a string that starts after Version= using the wildcard and replace it with a new string.
The output of the above PowerShell script to replace string with wildcard is:
PowerShell replace() method doesn’t use the regular expression hence it can’t perform the matching pattern. We will have to use PowerShell replace operator.
Cool Tip: How to replace a line in a file in PowerShell!
The other way to find all text that starts after the given string and replace it with a new string is by using the regex expression in PowerShell replace operator.
Let’s consider the above example, where we want to search for all text after Version= and replace it with a new text in the PowerShell string is:
$str = "Assembly Version=22.214.171.124" # Use the regex expression to replace text $str -replace 'Version=.+$','Version=126.96.36.199'
In the above PowerShell script, the $str variable stores the string data.
Using the PowerShell replace operator with regex expression .+$ to look for one or more characters up to the end of the string, it replaces Version=188.8.131.52 with the new string Version=184.108.40.206
The output of the above PowerShell script after replacing a text in a string is:
PS C:\> $str = "Assembly Version=220.127.116.11" PS C:\> $str -replace 'Version=.+$','Version=18.104.22.168' Assembly Version=22.214.171.124 PS C:\>
Cool Tip: How to use wildcards with variables in PowerShell!
I hope the above article on how to use PowerShell replace operator to replace wildcard or use the regex expression to find and replace new strings.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.