Three times a week (Monday/Wednesday/Friday), John Savill tackles your most pressing IT questions.
Read through the FAQ archives, or send him your questions via email.
Today: See how to use PowerShell for searching and replacing strings in files, understanding the difference between items that match or contain search results, and using single character wildcards in your PowerShell commands.
Q. What is the difference between match and contains in PowerShell?
A. On first glance these sounds like they would do the same thing but they are built to do very different things.
Match is designed to find a string within another string, for example find "grape" in the string "grapes," while
contains searches an array of objects to see if it contains a specific object. Try running the following PowerShell commands, as they illustrate the difference between the two types of queries. Look at the result of each. Note that to use
match at the end you must point at a single item and not the entire array.
$strings = ("apples","lemon","orange","grapes")
$strings -contains "apple"
$strings -contains "grape"
$strings -contains "grapes"
$strings -match "apple"
$strings -match "apple"
$strings -match "grape"
match to see if a string contains another string within it, while
contains looks to see if an array of objects includes a specific object.
-Like can behave similar to
-Match if you use wildcards with the
$strings -like "ple"
$strings -like "*ple"
Q. Can I use single character with -like in PowerShell?
A. Yes, and this can be very useful. When you use
like it tries to find a match for the string you specify. However, if there is a certain character that could be anything, you can single character wildcard with ?, for example:
$year = "born in 1975"
$year -like "*19?5"
This is more specific than simply putting a wildcard (*) between 19 and 5 which would then potentially match other things you would not want to match on.
Q. What's an easy way for replacing strings in a file with PowerShell?
A. The shortest method I have found is the following:
$attendfile = "w:\windows\panther\unattend.xml"
(Get-Content $attendfile).Replace('TSCAEDPH',$computename) | Set-Content $attendfile
If you break down what it is doing, you can walk right through the steps. This method:
- Sets a variable with the name of the file.
- Reads in the content of the file using Get-Content which results in a string.
- The Replace function of String is then called to perform the replacement.
- The resulting string is sent down the pipeline to Set-Content where it is written back out to the file.