PowerShell:recursively find and update text


This was um inspired by a requirement which boiled down to this:

Step 1

Given a root folder, first tell me all the extensions that you find under that root, so that I can make a judgment about which file types I want to update, so that their text content. For example, if I saw .xml and.txt, then I might want to update those, but if I saw, say .jpg and .JPG and .giF, then I don’t want to update those. And note I want a case-insensitive search doing: in the jpg case above, I expect you to find the .jpg, and .JPg, and jpG etc.

So let us do that first:

$uniqueExtensions = gci -Recurse | Select-Object Extension -Unique


I have built a set of dumb folders and files to test this. See here.

$searchString = ‘bank’
$replaceString = ‘tornado’
$rootDir = ‘C:\temp4’

cd $rootDir
“*** Searching for files in [$pwd] containing [$searchString] ***”

#gci -Recurse | Select-Object Extension -Unique
$fileList = gci -Recurse -Path .\* -Include *.txt, *.ext

$fileList | % {
$file = $_.FullName
$content = Get-Content $file
if ($content -like “*$searchString*”) {
“[$file]: found search string [$searchString], replacing with [$replaceString]”
(Get-Content $file).Replace($searchString, $replaceString) | Set-Content $file


See here for the code as well, and here for a set of folders and files you can use to test it.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s