Saturday, 9 April 2011

Renaming date-named folders using PowerShell

Since I've been using the Windows 7 Import Pictures and Videos wizard to upload photos from our digital camera, we've used the directory naming scheme of YYYY-MM-DD. Prior to this, I'd written my own custom photo importer in C++ as I didn't like the naming schemes that Windows XP offered. Unfortunately I'd chosen YYYYMMDD instead.

I'm now consolidating all our digital photos onto our Windows Home Server. This makes them easier to browse on the big screen using Windows Media Center, and has the added benefit that they also get backed up to the cloud via a subscription to CrashPlan.

I discovered the downside to having the different naming schemes when you go to view the photos in Media Center – it displays the folders out of order because they don't all follow the same format.

PowerShell to the rescue:

cd \\homeserver\photos
dir | Where-Object {$_.Name -match "^\d{8}$" } | Rename-Item -NewName { $_.Name -replace "^(\d{4})(\d{2})(\d{2})(.*)", "`$1-`$2-`$3`$4" }

This finds directories matching the old naming scheme and renames them to conform to the new one.

My C++ importer imported all photos into a single folder, so to avoid overwriting the same folder if you imported twice on the same day, I would add a .0 (or .1 etc) to the end of the folder to ensure it was unique. There weren't too many of these though, so I dealt with them manually.

No comments: