by Klaus Graefensteiner
6. April 2010 08:09
Introduction
Did you ever try to use ITunes or Windows Media player on a computer that doesn’t have an internet connection to retrieve album data? And then, did you also try to export a set of CDs, like an audio book, as mp3 files?
Then you might be familiar with file names like this:
C:\Users\Klaus\Music\Book1\CD01\Unknown Artist\Unknown Album (12-31-2009-4-31-10 PM)\01 Track1.mp3

Figure 1: Challenging file names
Now imagine you would like to get these files onto an MP3 player. You are out of luck here, because the resulting file names are neither unique nor sequential.
Solution
This is were the PowerShell script that is subject of this article safes your day. It will convert a file like the one mentioned in the introduction to a file names like this:
C:\Book1\B1_01_001.mp3
This file name contains the name of the book, the CD number and the track number. These files can be sorted alphabetically and then play the audio book in the correct sequence on your media player.
Figure 2: Debug output demonstrating the file renaming

Figure 3: The result after running the renaming script. All tracks in one folder with names that can be sorted in the correct sequence
#Example Path: C:\Users\Klaus\Music\Book1\CD01\Unknown Artist\Unknown Album (12-31-2009-4-31-10 PM)\01 Track1.mp3
#Result: C:\Book1\B01_01_001.mp3
$DebugPreference = "Continue"
function Flatten-Namespace([string] $SourcePath, [string] $FlatFilePrefix, $TargetPath)
{
$MP3Files = dir -Path $SourcePath -Recurse -Include *.mp3 -Force
Write-Debug $MP3Files.Count
$Regex = '^(.+?)(CD)(?<CD>\d{2})(.+?)( Track)(?<TRACK>\d{1,2})(\.mp3)$'
$MP3Files | ForEach-Object `
{
Write-Debug $_.Fullname
if ($_.Fullname -match $Regex)
{
$CD = "{0:00}" -f [int32] $matches.CD
$Track = "{0:00}" -f [int32] $matches.TRACK
$NewFileName = $FlatFilePrefix + "_" + $CD + "_" +$Track + ".mp3"
$NewFullName = Join-Path -Path $TargetPath -ChildPath $NewFileName
Write-Debug $NewFullName
Move-Item -Path $_.Fullname -Destination $NewFullName -Force
}
}
}
Flatten-Namespace -SourcePath "C:\Users\Klaus\Music\Book1" -FlatFilePrefix "B01" -TargetPath "C:\Book1"
Download
The script file can be downloaded here:
Ausblick
This is another example of applying regular expressions for renaming files.