The replace() method is one of the easiest ways of replacing the strings in PowerShell.
In this post, we will provide a deep insight into PowerShell replace() method alongside its various use cases.
How to use the PowerShell replace() method?
Primarily, the purpose of the replace() method is to put some characters/set of characters in place of existing characters of a string. This section provides an insight into the working and uses of the replace() method in PowerShell.
Syntax
From the syntax, it is observed that the replace() method accepts two parameters, and these are defined as:
- OldString: The characters to find.
- NewString: The characters that will be replaced with the “OldString” characters.
Example 1: Replace characters/substring using replace() method
This example demonstrates how the sequence of characters can be replaced using the replace() method.
In the following code, a string is stored in a variable named $string and the replace() method is applied on that variable to replace “Tuv” with “def”:
> $string.replace("Tuv","def")
Run the script from the terminal as we did here:
It is observed from the output that the replace() method has replaced the characters and the output is displayed in the console.
Note: To run/execute a PowerShell script from a PowerShell terminal, you need to copy the complete path of the script in the terminal and hit enter. For more details on script’s execution, click here: How to run a PowerShell script.
Example 2: Replace a substring using the replace() method
To replace a string in PowerShell, you need to store a string in a variable. In the following code, the $string variable contains two substrings. The replace() method is applied on the $string variable to replace the substring named “cool” with a new substring named “beautiful”:
> $string.replace('cool','beautiful')
Let’s execute the script:
It is observed from the output that the “cool” has been replaced by the “beautiful”.
Example 3: Remove a substring using the replace() method
In PowerShell, the Replace() method is also used to remove the substring. In the below example, the substring “cool” will be removed (basically it will be replaced with ‘’) using the replace() method:
> $string.replace('cool','')
Execute the script to get the result:
The output is showing the second argument only, not the first one, because the first substring is removed using the replace() method.
Conclusion
The PowerShell replace() method replaces the matched characters in a string. The replace() method matches the characters provided by the user and replaces them with a substring/character. The replace() method also assists in characters/substrings. This article provides a detailed overview of the replace() method in PowerShell and its use cases via examples as well.