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
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
a little bit modification without taglib-sharp
Function Get-VideoDetails {
param ($targetDirectory)
$LengthColumn = 27
$objShell = New-Object -ComObject Shell.Application
Get-ChildItem -LiteralPath $targetDirectory -Include *.avi -Recurse -Force | ForEach {
if ($_.Extension -eq ".avi"){
$objFolder = $objShell.Namespace($_.DirectoryName)
$objFile = $objFolder.ParseName($_.Name)
$Duration = $objFolder.GetDetailsOf($objFile, $LengthColumn)
New-Object PSObject -Property @{
Name = $_.Name
Duration = $Duration
}
}
}
}
# Supply your video directory
Get-VideoDetails "C:\Videos"
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.
精彩评论