Today With PowerShell – 3rd September 2016

Today I used PowerShell with the TagLibSharp library to fix, then break, then fix again the ID3 tags on some of my music files.

We buy a lot of compilation CDs here and tend to end up with correctly tagged but unhelpfully named files. Using TagLibSharp I can construct the filenames I need.

$taglib = "C:\bin\taglib-sharp.dll"
$sharedMusic = "\\server\Shared Documents\Shared Music\"
$mediaArtist = "Various Artists"
$mediaAlbum = "Now Thats What I Call PowerShell"
$albumPath = "$($sharedMusic)$($mediaArtist)\$($mediaAlbum)"
$mediaFiles = Get-ChildItem -LiteralPath $albumPath -Filter '*.mp3'

ForEach ($file in $mediaFiles) {

    $mediaFile = [TagLib.File]::Create($file.FullName)
    $titleTag = $mediaFile.Tag.Title
    $tag = $titleTag -split " / "
    $fileArtist = $tag[0]
    $fileTitle = $tag[1]
    $mediaFile.Tag.Artists = $fileArtist
    $mediaFile.Tag.AlbumArtists = $mediaArtist
    $mediaFile.Tag.Title = $fileTitle
    $newFileName = "$($albumPath)\$(($mediaFile.Tag.Track).ToString("00"))-$($fileTitle).mp3"
    Rename-Item -Path $file.FullName -NewName $newFileName


Hopefully this is all fairly clear but I’ll explain anyway.

In line 01 I establish a variable for the path to the TagLibSharp library file on my local PC. I load the library in line 02. Lines 03 to 06 set up some variables that build a path to the particular folder containing the files I want to fix. Line 07 grabs me a collection of all the MP3s in the folder, which I then iterate through. Line 11 gives me an object for the current file which surfaces the tags for the file. In my particular instance I want to fix the Title tag and rename the file based on it’s new title, as well as fixing the track artist. Lines 10 to 16 grab the tags and fix them. I commit the changes in line 19. In line 20 I create a new file name and rename the file in line 21. Simple!



This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s