A Handy Trick I’ve Started to Use a Lot

If you’re like me, you hate to do the same thing over and over.  That’s what programming is for, right?  To handle automating tedious procedures?  Unfortunately, it’s not at all appropriate to run off and build an app every time you need to do the same thing 3 times.  If you try that, you’ll have a lot of chances to write apps,  but probably will be looking for a new job because it takes you way too long to get anything accomplished.

Scripting is the short answer to the dilemma above.  PowerShell is one of the latest entries into the scripting world, and to my tastes, one of the best.

Here’s something I used several times in the last few days.  I can’t remember quite where I saw it first, but it was in a PowerShell blog about looping (I think).

Anyway, the problem is that I needed to edit config files on the servers in a farm.  Fortunately, the servers were numbered sequentially.  So, what I wrote was (suitably sanitized for public consumption):

1..9 | % { notepad "server$_`c$path_to_config_file\config.file" }

That popped the first 9 files up in notepad, ready to be edited.  The trick is to use the range syntax to create a list of numbers, and use % to loop through them.

If you need a longer range (with leading zeroes, of course), it’s not too hard.

1..20 | % {notepad ("server{0:D2}\c$\path_to_config_fileconfig.file" -f $_)}

Here, we use the format operator with a D2 format specifier (2 digits, leading zeros).  See here for more examples of format operators in PowerShell.

When you’re dealing with dozens of servers, tricks like this can save you a lot of time.

Let me know what you think.  What “idioms” in PowerShell do you find yourself using a lot?

Mike

4 Comments

  1. Mike, I love your blog, but is there any way that you could change your RSS feed so we can get the entire contents of the post in through our feed readers? Thanks!

  2. Pingback: Episode 86 – Jason Shirk from the PowerShell team « PowerScripting Podcast

Comments are closed.