Replace in Files for PowerShell

A while back I restructured my website so that this blog no longer started at the root, instead starting from /blog. This was so that I could introduce some other web apps and have a subfolder for projects etc.

One of the pains of this restructure was modifying all the links – I thought I had caught all this with a Redirector HttpModule, but recently realised that for some reason I had not caught images embedded in the posts themselves.
Also it was becoming a pain having to remember to include the HttpModule in my web.config everytime I upgraded my blog (dasBlog)

I wanted it fixed properly this time, so grabbed a copy of all the XML files in my ‘content’ folder, copied them to a local folder and cracked open PowerShell…

I wanted every instance of changed to – not difficult, but this would also change valid urls such as to (note the /blog/blog in the url)

So I got everything I needed done with two ‘one liners’ in PowerShell…

dir | %{ $a = get-content $_ ; $a = $a -replace (“”, “”) ; set-content $_ $a }


dir | %{ $a = get-content $_ ; $a = $a -replace (“”, “”) ; set-content $_ $a }

All fixed…


GEO 51.4043197631836:-1.28760504722595 
  • In relation to this post I was asked the following question via email :

    Dear Ken,

    Thanks for the tip regarding replacing strings within a text file.

    Is there a way to specify multiple replacement strings? In UNIX SEd, you can specify the old and new string within a text file. Rather than wrting a bunch of one-liners, I was hoping to find a means to change multiple strings via a one-liner.


    Mike Ramirez

    The following one liner will do a replace in files, with the original/replacement text defined in a txt file (named dvr.txt in this case). You should of course make sure that the dvr.txt file is not in the folder you are currently in. Also the dvr.txt file contains the original and the replacemnet text on each line seperated by a comma (,)…

    $dvr = get-content "c:dvr.txt" ; dir | %{ $a = get-content $_ ; $dvr | %{ $a = $a -replace ($_.Split(‘,’)[0], $_.Split(‘,’)[1])} ; set-content $_ $a }