PowerShell批量重命名相机音视频文件序号异常问题排查
批量重命名文件时序号错乱的问题排查与解决
问题描述
编写了一段PowerShell脚本,用于按「最后修改时间(yyyyMMdd_HHmmss_)+文件序号+扩展名」规则批量重命名文件夹内的图片与视频文件。基础功能正常,但测试时序号排序异常:预期序号随文件时间顺序递增,实际序号错乱,且多次测试结果一致。
脚本代码:
Set-Location $PSScriptRoot $inc_pics = "*.jpg","*.png","*.bmp","*.jpeg","*.heic" $inc_vids = "*.mp4","*.avi","*.mpg","*.mpeg","*.mov" $included = $inc_pics+$inc_vids $files = Get-ChildItem -Path .\* -File -Include $included $files $x=1 if ($files.Count -gt 99) { $d = "{0:D3}" } else { $d = "{0:D2}" } cls Write-Host "`n---------------------" Write-Host "-- Renaming files: --" Write-Host "---------------------`n`n" foreach ($file in $files) { $newname = ( "{0}{1}{2}" -f $file.LastWriteTime.ToString('yyyyMMdd_HHmmss_'),($d -f ($x)), $file.Extension ) Rename-Item -Path $file.FullName -NewName $newname Write-Host `t $file.Name -ForegroundColor Yellow -nonewline ; Write-Host " is now " -ForegroundColor White -nonewline; Write-Host $newname -ForegroundColor Green -nonewline ; Write-Host `n $x++ } Read-Host "`nPress Enter to continue" sleep 1
预期重命名结果:
20171210_162727_01.jpg
20171210_162728_02.jpg
20171210_162729_03.mp4
20171210_162730_04.mp4
20171210_162731_05.jpg
实际重命名结果:
20171210_162727_01.jpg
20171210_162728_02.jpg
20171210_162729_04.mp4
20171210_162730_05.mp4
20171210_162731_03.jpg
问题原因
Get-ChildItem 默认的排序规则不是按最后修改时间排序,而是遵循文件系统的原生顺序(通常为文件名排序)。脚本直接遍历未排序的$files集合,导致序号递增顺序与文件修改时间顺序不匹配,最终出现序号错乱。
解决方法
在获取文件列表后,添加按LastWriteTime升序排序的逻辑,确保遍历顺序与文件修改时间从早到晚的顺序一致:
修改$files的赋值语句,追加Sort-Object处理:
$files = Get-ChildItem -Path .\* -File -Include $included | Sort-Object LastWriteTime
完整修正后的脚本:
Set-Location $PSScriptRoot $inc_pics = "*.jpg","*.png","*.bmp","*.jpeg","*.heic" $inc_vids = "*.mp4","*.avi","*.mpg","*.mpeg","*.mov" $included = $inc_pics+$inc_vids # 关键修改:按最后修改时间升序排序文件 $files = Get-ChildItem -Path .\* -File -Include $included | Sort-Object LastWriteTime $x=1 if ($files.Count -gt 99) { $d = "{0:D3}" } else { $d = "{0:D2}" } cls Write-Host "`n---------------------" Write-Host "-- Renaming files: --" Write-Host "---------------------`n`n" foreach ($file in $files) { $newname = "{0}{1}{2}" -f $file.LastWriteTime.ToString('yyyyMMdd_HHmmss_'), ($d -f $x), $file.Extension Rename-Item -Path $file.FullName -NewName $newname Write-Host `t $file.Name -ForegroundColor Yellow -NoNewline Write-Host " is now " -ForegroundColor White -NoNewline Write-Host $newname -ForegroundColor Green Write-Host `n $x++ } Read-Host "`nPress Enter to continue" sleep 1
额外说明
- 若需按修改时间从晚到早排序,可在
Sort-Object后添加-Descending参数:Sort-Object LastWriteTime -Descending - 排序依据可根据需求替换为
CreationTime(文件创建时间)或LastAccessTime(最后访问时间)
内容的提问来源于stack exchange,提问作者SPJLee
相关产品推荐
相关产品推荐

