Thursday, March 27, 2008

Powershell Rename with Regex

I had a little more fun with Powershell today and I thought I'd share.

I used Visual Studio to generate a bunch of SQL Scripts into a Database Project. (In Server Explorer, right click -> Generate Create Script To Project).

This is very slick and works wonderfully. Only thing I didn't like is it puts the database name at the front of the file name:

I'm creating this project because I know I'm going to be executing these scripts against many databases, so I don't want the database in the name. I couldn't find a way to configure VS so it would generate the scripts with different names, so I'm stuck with them. That being the case, how do I easily rename all the files?

Powershell to the rescue!
dir | rename-item -newName { $_.Name -replace '^Database.', '' }

This command will rename every file in the current directory, removing the "Database." prefix from the name (if it has one).

You can use the shorthand version of the command and parameters as well:
dir | ren -new { $_ -replace '^Database.', '' }

I'm just so happy to finally have a powerful command line in Windows.


  1. That was handy. Thanks.

    Not sure how to escape the . character tho. Doesn't seem to work like in a normal regex with a \

  2. Just create a character expression if you wish to escape the period character.

    To do this simply place the character you wish to use inside square brackets like so: