Introduction to Windows PowerShell -Replace Operator
The first point to note with -Replace is we are discussing a PowerShell operator, it works in a similar fashion to its cousin -Match. Secondly, these comparison operators need input from a cmdlet such as Get-Content.
Introduction to -Replace
Before you call for the -Replace operator, you need to obtain stream of text, only then can you define the pattern to search for, and the pattern to replace. For example, you have a document where you wish to update a string of characters – say Code2013, with new values – say Code2014. Alternatively, you may be trying a more complex search and replace operation. My point is PowerShell's -Replace is a bit-Part in a bigger script drama.
Topics for PowerShell -Replace String
- Example 1: Select-String Then -Replace
- Example 2: PowerShell -Replace with Get-Content
- Example 3: PowerShell's -Replace with Special Characters
- Summary of -Replace
♣
Example 1: Select-String Then -Replace
Let us build up slowly; before we use the -Replace operator, let us have a refresher on Select-String. The key to understanding Select-String is studying the two main switches -Path and -Pattern. They say to me ‘Where is the input?’ and ‘What pattern do you want to match?’.
Example 1a: Select-String, ForEach-Object and -Replace
Remember we are building up gradually; I have not forgotten our goal, which is replacing "Guido" with "Guy".
Assumptions:
We have a file called gopher.txt.
Within this text file is the word "Guido".
# Stage 1: Preparation – just finding the text
Select-String -Path "C:\Change\gopher.txt" -Pattern "Guido"
# Expected result:
C:\Change\gopher.txt:3:Guido is king
Note 1: :3: Means line number 3
:Guido is king Refers to the line where the Pattern "Guido" occurs.
Example 1b: Conditional Operator -Replace into Action
# Stage 2: -Replace actually makes a change
Select-String -Path "C:\Change\gopher.txt" -Pattern "Guido" |
ForEach-Object {$_ -Replace "Guido", "Guy"}
# Expected result after -Replace:
C:\Change\gopher.txt:3:Guy is king
Note 2: Observe the important role played by ForEach-Object, it supplies a stream of text, and passes it to the {Block Statement containing -Replace}.
Note 3: The placeholder is just $_ no dot or property is required.
Guy Recommends: A Free Trial of the Network Performance Monitor (NPM)
v11.5
SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.
What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.
Download a free trial of Solarwinds’ Network Performance Monitor
Example 2: PowerShell -Replace with Get-Content
My idea in Example 2 is to choose a different cmdlet to provide the text stream. Our task is to correct a common problem, namely finding a repeated word such as "the the", and replacing with a single instance of "the".
Tasks for the -Replace Operator
- Get-Content reads the file then | pipes a stream of data.
- ForEach-Object provides a loop construction to process each item.
- -Replace takes "the the" and substitutes a single "the".
- Set-Content writes the result back to the original file.
# Example of PowerShell replacing text
Clear-host
$Location = "C:\Change\report.txt"
$Change = Get-Content $Location
$Change | ForEach-Object {$_ -Replace "the the", "the"} | Set-Content $Location
# Below are two optional items for testing
# $Change | ForEach-Object {$_ -Replace "the", "the the"} | Set-Content $Location
# Invoke-Item $Location
Note 4: Because -Replace is an operator, here it needs the {block} supplied by ForEach-Object.
An Example of even simpler syntax for -Replace:
Clear-host
"Humour my Neighbour's favourite colour!" -Replace "our", "or"
Humor my Neighbor's favorite color!
Guy Recommends: Free WMI Monitor for PowerShell
Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.
Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.
Download your free copy of WMI Monitor
Example 3: PowerShell's -Replace with Special Characters
The task here is to replace special characters such as brackets in filenames. We will be using Get-ChildItem as the vehicle. Here is a break-down of the three tasks.
- Create the files with Set-Content (Optional).
- Employ the Rename-Item cmdlet.
- Replace the brackets, using the escape character "\".
3a) Preparation: Create a series of files starting with Bracket(0)
# The only purpose of this script is to create files for testing.
Clear-Host
$Brackety = "C:\Change"
For($i=0;$i -le 6; ++$i) {
Set-Content -Path $("$Brackety\Stuff($i).txt") -value $i
}
Note 5: You may wish to change the value of $Brackety.
Note 6: If you experience formatting problems add -f $i, thus:
("$Brackety\Stuff($i).txt" -f $i)
3b) Replace in Action: Removing (brackets)
$Brackety = "C:\Change"
Get-ChildItem $Brackety | Rename-Item -NewName { $_.name -Replace "\(","" }
#Get-ChildItem $Brackety | Rename-Item -NewName { $_.name -Replace "\)","" }
Invoke-item $Brackety
Note 6: To remove the closing bracket cut the # (hash) at the start of line 3, and paste this # at the start of line 2.
Note 7: Observe how the "\" escapes the bracket to make PowerShell treat the next character as pure text rather than part of the command's syntax.
Research PowerShell's -Replace Operator
For learning more about operators such as -Replace try PowerShell's built-in Get-Help about_
Clear-Host
Get-Help about_Operators
Another source of ideas is to study similar PowerShell operators, for example:
Summary of PowerShell -Replace
This is a classic example of building a script gradually. Master the basics of Select-String, and only then focus on the -Replace operator. Remember that firstly you need to obtain stream of text. Once you connect to that input stream, then you can define the pattern that you are seeking to replace.
If you like this page then please share it with your friends
See more examples of PowerShell syntax
• PowerShell Tutorials • Syntax • PowerShell functions • Plist • RegEx • -Com
• PowerShell -confirm • WhatIf • -Match • -Like • -Online • Where • Free WMI Monitor
• -ErrorAction • -Replace • Windows PowerShell • PowerShell module directory
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.