Windows PowerShell -Replace (Search and Replace)Introduction to Windows PowerShell Select-stringThe first point to note with -Replace is that it is a parameter or a switch, therefore needs preceding command. One way of preparing a text string for a search and replace operation is by using get-content. Introduction to: Select-stringTo begin with you need to obtain stream of text, once you have the path to the input, then you need to define the pattern that you are seeking. As you are reading this I expect you are thinking of possible application for this command. 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 that Select-string may be merely a bit-part in a bigger drama. What ever you use for Select-string it's worth mastering the basics and being aware of the options. Topics for PowerShell Select-string
♣ Example 1 Select-string -path -patternThe 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. To be successful 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. What is even more important is that I navigate in powershell to the folder where I store the files with the patterns I am testing. Here are three simple scripts which all produce the same result using slightly different methods. By studying all three you will gain both perspective and ideas for the best method for your scripts.
Assumptions: Example 1a Select-string using variable $Location$Location = "D:\powershell\stuff\gopher.txt"
Expected outcome:
:3: Means line number 3 Example 1b Select-string (Pure no extra commands)select-string -path "D:\powershell\stuff\gopher.txt" -pattern "Guido" Example 1c -replace (Guy's indulgence)My main idea in Example 1c is to build on select-string and now 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. clear-Host Note 1: The purpose of `n is to force a carriage return.
Guy Recommends: SolarWinds Engineer's Toolset v10
|
||||||
Download my ebook:
|
*
|
|
|
|
Home Copyright © 1999-2009 Computer Performance LTD All rights reserved Please report a broken link, or an error. | |