Home » PowerShell » PowerShell Replace with Wildcard

PowerShell Replace with Wildcard

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=1.0.0.0“

You want to replace all text that starts after the string Version= with a new string Version=1.0.0.1

$str = "Assembly Version=1.0.0.0"

$str -replace 'Version=.*?.*','Version=1.0.0.1'

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 String with WildCard
PowerShell Replace String with WildCard

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=1.0.0.0" 
# Use the regex expression to replace text
$str -replace 'Version=.+$','Version=1.0.0.1' 

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=1.0.0.0 with the new string Version=1.0.0.1

The output of the above PowerShell script after replacing a text in a string is:

PS C:\> $str = "Assembly Version=1.0.0.0"                                                                               

PS C:\> $str -replace 'Version=.+$','Version=1.0.0.1'                                                                   
Assembly Version=1.0.0.1

PS C:\> 

Cool Tip: How to use wildcards with variables in PowerShell!

Conclusion

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.