Powershell 重命名相机图片和视频并附加编号

问题描述 投票:0回答:1

我尝试在 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

这可能是显而易见的事情,但我不知道是什么原因造成的。目录之间似乎没有模式,但是如果在恢复的目录上重复多次,结果总是相同的

这主要是为了防止重复的文件名(其中多张照片在一秒内拍摄,我想另一种方法是在末尾添加(1),(2)(我的手机对普通项目执行此操作,并且001,002 等连拍图片)

powershell scripting
1个回答
0
投票

看起来您的意图是将序列编号基于文件的上次写入时间戳暗示的时间顺序。

因此,替换:

foreach ($file in $files)

与:

foreach ($file in $files | Sort-Object LastWriteTime)
© www.soinside.com 2019 - 2024. All rights reserved.