根据照片拍摄时间批量重命名文件

这几天一直想给照片搞个备份,在寻找一个性价比比较高而且又比较稳定的方案,现在还没找到,先进行图片整理工作。整理过程中想把所有文件名统一一下,于是总结了这个脚本。

需要提前从 exiftool.org 下载 exiftool.exe,用于读取图片或视频的 EXIF 信息。

PowerShell 脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
$currentDirectory = Get-Location

# 处理图片
$imageFiles = Get-ChildItem -Path $currentDirectory -File |
Where-Object { $_.Extension -match '\.(jpg|jpeg|png|gif)' }

foreach ($imageFile in $imageFiles) {
$dateTaken = & "D:\exiftool.exe" "-DateTimeOriginal" "-d" "%Y%m%d_%H%M%S" "-s" $imageFile.FullName
$dateTaken = $dateTaken.Trim() -replace ".*: ", ""
if ($dateTaken -ne "") {
$newFileName = "IMG_$dateTaken$($imageFile.Extension)"
$newFilePath = Join-Path -Path $currentDirectory -ChildPath $newFileName
while (Test-Path $newFilePath) {
$year = [int]($dateTaken.Substring(0, 4))
$month = [int]($dateTaken.Substring(4, 2))
$day = [int]($dateTaken.Substring(6, 2))
$hour = [int]($dateTaken.Substring(9, 2))
$minute = [int]($dateTaken.Substring(11, 2))
$second = [int]($dateTaken.Substring(13, 2))
$newDate = Get-Date -Year $year -Month $month -Day $day -Hour $hour -Minute $minute -Second $second
$newDate = $newDate.AddSeconds(1)
$dateTaken = $newDate.ToString("yyyyMMdd_HHmmss")
$newFileName = "IMG_$dateTaken$($imageFile.Extension)"
$newFilePath = Join-Path -Path $currentDirectory -ChildPath $newFileName
}
Rename-Item -Path $imageFile.FullName -NewName $newFilePath -Force
}
Write-Host $imageFile
}

# 处理视频
$videoFiles = Get-ChildItem -Path $currentDirectory -File |
Where-Object { $_.Extension -match '\.(mp4|mov|avi|mkv)' }

foreach ($videoFile in $videoFiles) {
$mediaCreateTime = & "D:\exiftool.exe" "-MediaCreateDate" "-d" "%Y%m%d_%H%M%S" "-s" $videoFile.FullName
$mediaCreateTime = $mediaCreateTime.Trim() -replace ".*: ", ""

if ($mediaCreateTime -ne "") {
$newFileName = "VID_$mediaCreateTime$($videoFile.Extension)"
$newFilePath = Join-Path -Path $currentDirectory -ChildPath $newFileName

if ($videoFile.Name -ne $newFileName) {
Rename-Item -Path $videoFile.FullName -NewName $newFilePath -Force
}
}
Write-Host $videoFile
}

Write-Host "重命名完成。"

图片重命名为 IMG_YYYYMMDD_HHMMSS.ext,视频为 VID_YYYYMMDD_HHMMSS.ext。如果目标文件名已存在,自动递增一秒避免冲突。

Notice: 正常情况下,这里会有一个基于utteranc.es的留言系统,如果看不到,可能要想想办法才能看到。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2012 - 2026 tiaobug.com All Rights Reserved.

鲁ICP备2024124237号-1