Export Songs in iTunes Playlist and Maintain Folder Hierarchy
Today I needed to copy a large number of albums from my iTunes collection to a USB drive. I could have added the albums to a playlist for easy selection, and then dragged the selected files to a folder on the USB drive. Unfortunately, this method puts all the files in a single folder, when what I really wanted was to maintain the hierarchical structure of the iTunes library (of songs stored in folders named after the album, and albums stored in folders named after the artist). To meet this requirement, I developed a small script that leveraged the iTunes SDK.
The script retrieves all songs from the playlist defined by the variable sPlaylist. It then copies each song to a subfolder of the location defined by sTarget, maintaining the original folder hierarchy of the iTunes library.
There are 4 prerequisites for using this script. The first is that iTunes is configured to keep the media folder automatically organised, and that songs are stored in a 2-level hierarchy, arranged first by artist, and then by album. The second is that iTunes installed on a Windows computer. The third is that you've added the albums you want to export into a playlist with the name specified by the sPlaylist variable. And finally, that the variable sTarget accurately identifies the location to which the files should be copied.
Save the code into a file named C:\Temp\exportpl.js, open a command prompt, navigate to C:\Temp, and then run the following command:
cscript.exe exportpl.js
Note: Ensure you include two backslashes between the subfolders specified in the sTarget variable.
var sTarget = "E:\\Music"
var sPlaylist = "Export"
var oFSO = WScript.CreateObject("Scripting.FileSystemObject");
var iTunesApp = WScript.CreateObject("iTunes.Application");
var cSources = iTunesApp.Sources;
var oSource = cSources.ItemByName("Library");
var cPlaylists = oSource.Playlists;
var oPlaylist = cPlaylists.ItemByName(sPlaylist);
var oTracks = oPlaylist.Tracks;
var iNumTracks = oTracks.Count;
for (var i = 1; i <= iNumTracks; i++) {
var oTrack = oTracks.Item(i);
var cMatch = oTrack.Location.match(/.*[\\]([^\\]+[\\][^\\]+[\\])[^\\]+\.\w+$/);
var sTargetPath = sTarget + "\\" + cMatch[1];
var cFolders = sTargetPath.split("\\");
var sCurrentFolder = ""
for (var j in cFolders) {
sCurrentFolder = sCurrentFolder + cFolders[j];
if (!oFSO.FolderExists(sCurrentFolder)) {
oFSO.CreateFolder(sCurrentFolder);
}
sCurrentFolder = sCurrentFolder + "\\";
}
oFSO.CopyFile(oTrack.Location, sTargetPath, true);
}