Tuesday 21 July 2015

A PowerShell script to copy files listed in a M3U playlist to a destination folder whilst preserving directory structure

Some background to this script:


  • I have a large music collection, but only limited space on my phone, so I only want to copy a subset of the files
  • I use Logitech Media Server (a.k.a. Squeezebox Server), along with Erland's Trackstat, Playlist Generator and SQL Query plugins, which automatically generates me M3U format playlist files of things like the most recently added tracks, most played, highest rated etc.
  • I wanted to use some of these generated playlists to specify which files to copy to a destination folder, and so I wrote the script below with a lot of help from sources on Google!
  • Challenges included preserving the directory structure when copying each file, and handling directory names and file names with characters such as square brackets, which apparently have special meaning in PowerShell.





$sourcePlayList="X:\playlists\My Music - Last 500 Added.m3u"
$outputPath="M:\S6\music\"
$regExKeep="volume1\/music\/.*"
$regExExclude="#EXTURL:.*"
$rawPlayListValues = Get-Content $sourcePlayList



foreach ($item in $rawPlayListValues) {
  #First extract the path
  if($item -match $regExExclude){
  }
  elseif($item -match $regExKeep){
   $item = $matches[0] -replace "volume1\/music\/",""
   
   $sourceitem = "X:\$item"
   $sourceitem = Get-Item -Literalpath $sourceitem
   
   $dir = $sourceitem.DirectoryName.Replace("X:\",$outputPath)
   
   $target = $sourceitem.FullName.Replace("X:\",$outputPath)

            if (!(test-path -LiteralPath $dir)) 
   {
    mkdir $dir
   }
   
   if (!(test-path -LiteralPath $target))
   {
    Copy-Item -Literalpath $sourceitem.FullName -Destination $target -Recurse -Force
   }

   Write-Host $item
  } 
}

1 comment:

  1. Coin Casino Review 2021 - Casinowow
    Check out the 코인카지노 추천인 complete casino review and learn about Coin Casino. Check out the range of games, bonuses and promotions at CasinoWow.Casino: 10GAMBLER GamesFeatures: No Deposit Bonus, Free Spins, Rating: 9.2/10 · ‎Review by CasinoWow

    ReplyDelete