PowerShell supports the use of regular expressions, which enables you to perform text replacements with wildcard patterns.
Method 1: Use the -replace operator to replace text with wildcard patterns
$newString = $original_string -replace $pattern,$replacement_string
This example replaces the text matched by the wildcard pattern $pattern
in the $original_string
with the replacement string $replacement_string
.
The following examples demonstrate the replacement of text with wildcard patterns in PowerShell.
Using the -replace Operator to Replace Text with Wildcard Patterns
To replace text with a wildcard pattern to match the text you want to replace in PowerShell, we can use the -replace operator with a regular expression that includes the wildcard.
This example replaces all text matching by the wildcard patterns with the “X” in a given string $original_string
.
$original_string = "The numbers 1, 2, and 3" $pattern = '[0-9]' $new_string = $original_string -replace $pattern, 'X' Write-Host $new_string
The output of the above PowerShell script is given below:
![PowerShell replace text with wildcard patterns in a string](https://activedirectorytools.net/wp-content/uploads/2024/04/powershell-replace-text-with-wildcard-patterns.webp)
The $original_string
stores the string. $pattern
variable contains the wildcard pattern [0-9]. We have used the -replace operator to search for the given $pattern
in the $original_string and replace them with the new string “X“.
Finally, the modified string $new_string
is output using the Write-Output
cmdlet in PowerShell.
Conclusion
I hope the above article on how to replace the text with wildcard patterns in PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.