Wednesday, June 12, 2013

Search and replace using PowerShell

 

Last week we were faced to a problem: there are numerous files distributed in hierarchy of folders on the disk and we are required to replace a pattern string in each of these files to a specified replacement string. (In fact, we had to add quickly hardwired location parameters to all the AJAX ModalPopupExtender controls in an ASP.NET solution).

The challenge is: the files cannot be copied outside of the target machine, processed and copied back – all the processing MUST occur on the target box using only on-board tools. And there aren’t any built-in software in Windows (Server 2008 R2) providing such functionality like S&R, Visual Studio or other similar tools, enabling recursive search and replace operations.

Some of us started to wipe dust off their DOS command line skills and write some batch files. But the better solution is in use of built-in PowerShell.

Start PowerShell and launch following command:

dir –r {fileseach pattern}| %{ $x = get-content $_ ; $x = $x -replace ({search pattern}, {replacement pattern}) ; set-content $_ $x }

For example:

dir -r *.aspx| %{ $x = get-content $_ ; $x = $x -replace ("ModalPopupExtender ID", "ModalPopupExtender X=""100"" Y=""100"" ID") ; set-content $_ $x }

replaces string

ModalPopupExtender ID

with

ModalPopupExtender X="100" Y="100" ID

in all .aspx files in current folder and below

This makes from

<ajax:ModalPopupExtender ID=”mpe1” …/>

the string

<ajax:ModalPopupExtender X="100" Y="100" ID=”mpe1” …/>

So all the processing occurred on the target box without any need to copy the files to equipped machine, process them and copy back. Also without any need to install/deploy additional software to the target machine specially to perform desired processing.

Next time you need to replace some string with another one in a number of files distributed in recursive subfolders using only built-in software of Windows OS – do not panic: use pattern PowerShell command from above and enjoy!

Monday, June 10, 2013

Microsoft Azure VM billing model changed

Scott Guthrie announced at TechEd 2013 changes in VM billing model: you pay only for running - and not
as mentioned before also for stopped VMs.
So please disregard my previous post and enjoy!