PowerShell String stores the string data and provides sting manipulation and methods to replace string, replace substring in a string, replace characters, etc…
PowerShell has a replace() method and PowerShell replace operator to replace string or characters.
In this article, we will discuss how to use the PowerShell replace() method and PowerShell replace operator to replace substring in a string.
Replace Substring in PowerShell using replace() method
Let’s understand PowerShell replace substring with an example.
Let’s consider, that we have a string stored in the variable $str as given below
$str = "Welcome! Admin to ShellGeek!"
We would like to replace the substring Admin from the string with the string ShellAdmin so that the output string should have the value “Welcome! ShellAdmin to ShellGeek!“
To replace the substring in the given string in PowerShell, use the PowerShell replace() method.
$str.Replace("Admin","ShellAdmin")
In the above PowerShell script, we call the replace() method over the $str variable. It accepts the two arguments like string to find “Admin” and string to replace with “ShellAdmin“
The output of the above PowerShell script using replace substring in a string is:
WelCome! ShellAdmin to ShellGeek!
Cool Tip: How to replace multiple characters in a string using PowerShell!
Replace Substring in String in PowerShell using replace Operator
You can use PowerShell replace operator to replace substring in a string. PowerShell replace operator has two arguments similar to replace() method like string to find and string to replace with.
Let’s consider an example to understand replace operator replace text in a PowerShell string.
$str = "Welcome! Admin to ShellGeek!" $str -replace "Admin","ShellAdmin"
In the above PowerShell script, the $str variable stores the string. To replace substring in a string, we have used PowerShell replace operator and pass old value and new value as comma separated.
The output of the above PowerShell script after using replace operator to replace a text in a string is:
PS C:\> $str = "Welcome! Admin to ShellGeek!"
PS C:\> $str -replace "Admin","ShellAdmin"
Welcome! ShellAdmin to ShellGeek!
PS C:\>
Conclusion
I hope the above article on PowerShell replace substring using the PowerShell replace() method and PowerShell replace operator is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.