Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



Windows PowerShell -Replace (Search and Replace)

Introduction to Windows PowerShell -Replace Parameter

The first point to note with -Replace is that it is a parameter or a switch, therefore it needs input from another PowerShell cmdlet.  One way of preparing a text string for such a search and replace operation is by using Get-Content.

Introduction to: Select-String  -Replace

Before you call for the -replace parameter, first you need to obtain stream of text.  Once you connect to the input stream, then define the pattern that you are seeking.  As you are reading this I expect you are thinking of possible applications for this technique.  Perhaps you wish to find which documents contain a particular string, alternatively, you may be trying a more complex search and replace operation.  My point is -replace maybe a bit-part in a bigger drama.

Topics for PowerShell -Replace String

 ♣

Example 1 Select-String -path -pattern

Let us build up slowly, before we use the -replace parameter, let us have a refresher on Select-String and Get-Content.  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?'.

To ensure that my examples work, we need to agree on the file location and the pattern to search.  Thus for 'our' script to work you need to embrace one of two tactics, either mimic my folder structure and patterns, or amend the script to fit in with your environment.  My folder happens to be called : D: \powershell\stuff. 

Here are two simple Select-String scripts which produce the same result using slightly different methods.  By studying both you will gain both perspective and ideas for the best method for your scripts.

Assumptions:
You have a file called gopher.txt. 
In gopher.txt is the the word Guido.

Example 1a Select-String Using Variable $Location

Remember we are building up to replace string gradually.

# Basic preparation just finding the text
$Location = "D:\powershell\stuff\gopher.txt"
Select-String -path $Location -pattern "Guido"

Expected outcome:
D:\powershell\stuff\gopher.txt:3:Guido is king

:3:  Means line number 3
:Guido is king  Refers to the line where the Pattern "Guido" occurs.

Example of Select-String (Pure no extra commands)

# Stage 2
Select-String -path "D:\powershell\stuff\gopher.txt" -pattern "Guido"

See more about PowerShell Parameters

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft 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.

Download your free copy of WMI Monitor

Example 2 PowerShell -Replace (The Main Event)

My idea in Example 1b is to build on Select-String, now, at last, we are ready to replace one string with another.  Here is a common problem a repeated word "the the".  What I want to do is replace the double word with a single instance.

Replace Rationale

  1. Get-ChildItem locates all files beginning with 'g'.  Note the path.
  2. Get-Content reads the files
  3. A second foreach construction deals with the -replace "the the" operation.

# Example of PowerShell -replace parameter
clear-Host
$file = Get-ChildItem "D:\powershell\snippets\g*.txt"
foreach ($str in $file)
{
$content = Get-Content -path $str
$content | foreach {$_ -replace "the the", "the"} | Set-Content $str
}
write-Host "After replace `n"
$file

Note 1: The purpose of `n is to force a carriage return.

Note 2: Troubleshooting.  Remember this is an example, you need to create your own file, and you probably need to change the value of $file to suit your computer.

Note 3: See more about the Set-Content cmdlet.

Note 4: See more about the Remove-Item cmdlet.

Guy Recommends:  Solarwinds' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

Researching PowerShell's -Replace Parameter

Clear-Host
Get-Command | where { $_.parameters.keys -contains "replace"}

Much to my surprise the only cmdlet to feature -replace is Update-List.

Help update-List

-Replace <Object[]>
Specifies a new collection. This parameter replaces all items in the original collection with the items specified by this parameter.

Summary of PowerShell -Replace String

This is a classic example of building a script gradually.  Master the basics of Select-String, and only then focus on the -replace parameter.  Remember that firstly first you need to obtain stream of text.  Once you connect to the input stream, then define the pattern that you are seeking. 

If you like this page then please share it with your friends

 


See more PowerShell examples for syntax advice

PowerShell Tutorials  • Syntax  • PowerShell functions  • Plist  • RegEx  • -Com

PowerShell -confirm  • WhatIf  • -Match  • -Like  • -Online  • Where

-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.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

 

Home Copyright © 1999-2012 Computer Performance LTD All rights reserved

Please report a broken link, or an error.