视频时长分类脚本使用说明
本文档介绍如何使用 ffprobe
与 PowerShell 脚本,对视频文件按播放时长进行分组并移动,同时生成移动记录。
一、前提条件
目录结构
C:\Users\。。。 ├─ ffmpeg │ └─ bin │ ├─ ffprobe.exe │ └─ ffmpeg.exe └─ (待处理视频文件及子目录)
工具要求
- Windows 自带 PowerShell(建议管理员权限运行)。
ffprobe.exe
(同目录下无需安装,可便携使用)。
二、脚本文件
- 脚本名称:
SortByFfprobeDuration.ps1
- 建议存放路径:例如
C:\Users\hero\Desktop
脚本内容如下:
# —— 1. 定义根目录与 ffprobe 路径 ——
$root = 'C:\Users\。。。'
$ffprobe = Join-Path $root 'ffmpeg\bin\ffprobe.exe'
# —— 2. 定义时长分组区间(秒)与目录名 ——
$groups = @{
'Dur_≤1min' = { $sec -le 60 }
'Dur_1~3min' = { $sec -gt 60 -and $sec -le 180 }
'Dur_3~5min' = { $sec -gt 180 -and $sec -le 300 }
'Dur_5~10min' = { $sec -gt 300 -and $sec -le 600 }
'Dur_10~20min' = { $sec -gt 600 -and $sec -le 1200 }
'Dur_20~40min' = { $sec -gt 1200 -and $sec -le 2400 }
'Dur_gt40min' = { $sec -gt 2400 }
}
# —— 3. 创建分组文件夹 ——
foreach ($name in $groups.Keys) {
$dir = Join-Path $root $name
if (-not (Test-Path $dir)) {
New-Item -Path $dir -ItemType Directory | Out-Null
}
}
# —— 4. 遍历并分类 ——
$log = [System.Collections.Generic.List[string]]::new()
Get-ChildItem $root -Recurse -File |
Where-Object { $_.Extension -match '^\.(mp4|mkv|avi|mov|flv)$' } |
ForEach-Object {
# 4.1 抓取原始时长字符串
$raw = & $ffprobe -v error -show_entries format=duration `
-of default=noprint_wrappers=1:nokey=1 $_.FullName
if ([string]::IsNullOrEmpty($raw)) {
return
}
# 4.2 初始化并解析时长
[double]$d = 0
if (-not [double]::TryParse($raw, [ref]$d)) {
return
}
$sec = [math]::Floor($d)
# 4.3 分组移动
foreach ($grp in $groups.Keys) {
if (& $groups[$grp]) {
$targetDir = Join-Path $root $grp
$dest = Join-Path $targetDir $_.Name
Move-Item -LiteralPath $_.FullName -Destination $dest
$log.Add($dest)
break
}
}
}
# —— 5. 写入日志 ——
$log | Out-File (Join-Path $root 'moved_by_duration.txt') -Encoding UTF8
三、使用步骤
- 保存脚本
将以上脚本内容复制到SortByFfprobeDuration.ps1
,存放在方便的目录(如桌面)。 - 以管理员身份打开 PowerShell
在开始菜单中搜索 “PowerShell”,右键选择 “以管理员身份运行”。 设置执行策略
Set-ExecutionPolicy Bypass -Scope Process
切换到脚本目录
cd C:\Users\。。。
执行脚本
.\SortByFfprobeDuration.ps1
查看结果
- 在
00AAATTEEMMPPP01
目录下应出现 7 个分组子文件夹。 - 根目录下生成
moved_by_duration.txt
,记录所有移动后的文件路径。
- 在
四、注意事项
- 如有同名文件可能被覆盖,可自行在脚本中加入重命名逻辑。
- 如需支持更多视频格式,修改脚本中
.Extension -match
的正则。 - 若运行缓慢,可考虑分批或并行处理。