views:

171

answers:

2

Hi,

I have a directory of videos (.AVI files) that I want to determine the duration of, and to create a file listing the titles and durations of all the videos, sorted in descending order of the video duration.

Can anyone offer a PowerShell script to do this?

Thanks, MagicAndi

A: 

My initial script is below. I've no doubt this can be drastically improved on.

# Load TagLib DLL
[void] [Reflection.Assembly]::LoadFrom($TagLibDllPath)

# Get all videos in the given directory
$videoFiles = Get-ChildItem $directoryPath -Include *.avi -Recurse -Force

if (($videoFiles -eq $null) -or (($videoFiles | Measure-Object).Count -eq 0))
{
    Throw "Given directory $directoryPath does not contain any videos!"
}
else
{
    $videos = @()
    foreach($videoFile in $videoFiles)
    {    
        $video = [TagLib.File]::Create($videoFile.FullName) 
        $videoDetails = new-object object;
        $videoName = [System.IO.Path]::GetFileNameWithoutExtension($videoFile.FullName)

        Add-Member -in $videoDetails noteproperty "Title" $videoName
        Add-Member -in $videoDetails noteproperty "Duration" $video.Properties.Duration.TotalMinutes
        $videos+= $videoDetails;
    }

    $videos = $videos | Sort-Object Duration -descending

    if (!(Test-Path $outputFile))
    {
        New-Item -Path $outputFile -Type "file" -Force  | out-null 
    }

    $newLine = [System.Environment]::NewLine
    $fileHeader = "Duration (minutes)    Title"
    $fileContents = $fileHeader, $newLine

    foreach($video in $videos)
    {    
        $outputString = [string]::Format("{0}`t`t`t`t`t {1}", "{0:N0}" -f $video.Duration, $video.Title)                
        $fileContents = $fileContents + $outputString
    }

    Set-Content -path $outputFile -value $fileContents
} 

Please note the dependency on the TagLib Sharp library. Both $directoryPath and$outputFile are parameters passed to the script.

MagicAndi
+2  A: 

Based on MagicAndi's approach.

# Needs the path where your dll is
Add-Type -Path "C:\taglib-sharp.dll"

Function Get-VideoDetails {
    param ($targetDirectory)

    Get-ChildItem $targetDirectory -Include *.avi -Recurse -Force | ForEach {
        $video = [TagLib.File]::Create($_.FullName)

        New-Object PSObject -Property @{
            Name = $_.FullName
            Duration = $video.Properties.Duration.TotalMinutes
    }
}

# Supply your video directory
Get-VideoDetails "C:\Videos" | Sort Duration -Descending
Doug Finke
And that would be for use with PowerShell v2 only since it uses the new Add-Type.
Marco Shaw
Doug, thanks for your answer. +1
MagicAndi