如何批量重命名包含数字和修改日期的文件?
How to batch rename files including a number and the modified date?
编辑:我应该改用拍摄日期,因为我们正在处理的照片的修改日期有时会延迟一小时。
我正在尝试编写将文件重命名为以下格式的内容:
24024 25-12-2014 20.18.JPG
24025 26-12-2014 18.01.JPG
24026 26-12-2014 18.01.JPG
24027 30-12-2014 17.05.JPG
24028 31-12-2014 15.09.JPG
24029 31-12-2014 15.19.JPG
我需要这个来按照我父亲设计的方式整理我母亲的照片。我首先专门寻找使用 cmd 批处理文件执行此操作的方法,但它似乎太复杂了。我现在正在尝试使用 PowerShell。
我已经试过了,效果不错:
Get-ChildItem *.JPG | Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}
但我还没有设法包括一个变量计数。这不编译:
$a = 10; Get-ChildItem *.JPG | {Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}; $a++}
这也不行,我在另一个问题中发现了这一点。
Foreach ($Item in Get-ChildItem *.JPG) {Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}}
你可以这样做:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | ForEach-Object {
$_ | Rename-Item -NewName ('{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm")))
}
编辑 1
要按时间顺序命名,只需在脚本中添加一个Sort-Object
,如下所示:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | Sort-Object LastWriteTime | ForEach-Object {
$_ | Rename-Item -NewName ('{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm")))
}
编辑 2
根据您最后的评论,要从图像中的 Exif 数据中获取日期,如果可能,您需要一个从文件中获取 DateTimeOriginal
的函数。
您可以使用以下代码执行此操作:
function Get-ExifDate {
# returns the 'DateTimeOriginal' property from the Exif metadata in an image file if possible
[CmdletBinding(DefaultParameterSetName = 'ByName')]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = 'ByName')]
[Alias('FullName', 'FileName')]
[ValidateScript({ Test-Path -Path $_ -PathType Leaf})]
[string]$Path,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0, ParameterSetName = 'ByObject')]
[System.IO.FileInfo]$FileObject
)
Begin {
Add-Type -AssemblyName 'System.Drawing'
}
Process {
# the function received a path, not a file object
if ($PSCmdlet.ParameterSetName -eq 'ByName') {
$FileObject = Get-Item -Path $Path -Force -ErrorAction SilentlyContinue
}
# Parameters for FileStream: Open/Read/SequentialScan
$streamArgs = @(
$FileObject.FullName
[System.IO.FileMode]::Open
[System.IO.FileAccess]::Read
[System.IO.FileShare]::Read
1024, # Buffer size
[System.IO.FileOptions]::SequentialScan
)
try {
$stream = New-Object System.IO.FileStream -ArgumentList $streamArgs
$metaData = [System.Drawing.Imaging.Metafile]::FromStream($stream)
# get the 'DateTimeOriginal' property (ID = 36867) from the metadata
# Tag Dec TagId Hex TagName Writable Group Notes
# ------- --------- ------- -------- ----- -----
# 36867 0x9003 DateTimeOriginal string ExifIFD (date/time when original image was taken)
# see: https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
# get the date taken as an array of bytes
$exifDateBytes = $metaData.GetPropertyItem(36867).Value
# transform to string, but beware that this string is Null terminated, so cut off the trailing 0 character
$exifDateString = [System.Text.Encoding]::ASCII.GetString($exifDateBytes).TrimEnd("`0")
# return the parsed date
return [datetime]::ParseExact($exifDateString, "yyyy:MM:dd HH:mm:ss", $null)
}
catch{
Write-Warning -Message "Could not read Exif data from '$($FileObject.FullName)'"
}
finally {
If ($metaData) {$metaData.Dispose()}
If ($stream) {$stream.Close()}
}
}
}
使用该函数,您的代码将如下所示:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
# start a loop to gather the files and reset their LastWriteTime property to the one read from the Exif data.
# pipe the result to the Sort-Object cmdlet and enter another ForEach-Object loop to perform the rename.
Get-ChildItem -Path $Path -Filter '*.JPG' -File | ForEach-Object {
$date = $_ | Get-ExifDate
if ($date) {
$_.LastWriteTime = $date
}
$_
} | Sort-Object LastWriteTime | ForEach-Object {
$newName = '{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm"))
# output some info to the console
Write-Host "Renaming file '$($_.Name)' to '$newName'"
$_ | Rename-Item -NewName $newName
}
这使用字符串格式-f
。你给它一个模板字符串,在花括号之间带有编号的占位符。
第一个 {0:00000}
是一种格式化数字的方式,前面有零个字符,在这种情况下最多 5 个字符的长度。
第二个 {1}
被格式化的日期字符串替换。
使用 ++
语法,每次迭代都会增加 $Count
变量。
不使用 ForEach-Object 的 Theo 好答案 (+1) 的替代方法
as Rename-Item
直接接受管道输入。
这需要 -NewName
参数的脚本块,而 $count
需要是 [ref]
(参见来自 mklement0 的 )
-format operator 允许直接在占位符中应用格式字符串
$Path = 'D:\' # the folder where the jpg files are
$Count = [ref] 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | Sort-Object LastWriteTime |
Rename-Item -NewName {"{0:D5} {1:dd-MM-yyyy HH.mm}{2}" -f `
$Count.Value++,$_.LastWriteTime,$_.Extension} -whatif
如果输出看起来没问题,删除尾随 -WhatIf
参数
编辑:我应该改用拍摄日期,因为我们正在处理的照片的修改日期有时会延迟一小时。
我正在尝试编写将文件重命名为以下格式的内容:
24024 25-12-2014 20.18.JPG
24025 26-12-2014 18.01.JPG
24026 26-12-2014 18.01.JPG
24027 30-12-2014 17.05.JPG
24028 31-12-2014 15.09.JPG
24029 31-12-2014 15.19.JPG
我需要这个来按照我父亲设计的方式整理我母亲的照片。我首先专门寻找使用 cmd 批处理文件执行此操作的方法,但它似乎太复杂了。我现在正在尝试使用 PowerShell。
我已经试过了,效果不错:
Get-ChildItem *.JPG | Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}
但我还没有设法包括一个变量计数。这不编译:
$a = 10; Get-ChildItem *.JPG | {Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}; $a++}
这也不行,我在另一个问题中发现了这一点。
Foreach ($Item in Get-ChildItem *.JPG) {Rename-Item -newname {$_.LastWriteTime.toString("dd-MM-yyyy HH.mm") + ".JPG"}}
你可以这样做:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | ForEach-Object {
$_ | Rename-Item -NewName ('{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm")))
}
编辑 1
要按时间顺序命名,只需在脚本中添加一个Sort-Object
,如下所示:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | Sort-Object LastWriteTime | ForEach-Object {
$_ | Rename-Item -NewName ('{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm")))
}
编辑 2
根据您最后的评论,要从图像中的 Exif 数据中获取日期,如果可能,您需要一个从文件中获取 DateTimeOriginal
的函数。
您可以使用以下代码执行此操作:
function Get-ExifDate {
# returns the 'DateTimeOriginal' property from the Exif metadata in an image file if possible
[CmdletBinding(DefaultParameterSetName = 'ByName')]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = 'ByName')]
[Alias('FullName', 'FileName')]
[ValidateScript({ Test-Path -Path $_ -PathType Leaf})]
[string]$Path,
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0, ParameterSetName = 'ByObject')]
[System.IO.FileInfo]$FileObject
)
Begin {
Add-Type -AssemblyName 'System.Drawing'
}
Process {
# the function received a path, not a file object
if ($PSCmdlet.ParameterSetName -eq 'ByName') {
$FileObject = Get-Item -Path $Path -Force -ErrorAction SilentlyContinue
}
# Parameters for FileStream: Open/Read/SequentialScan
$streamArgs = @(
$FileObject.FullName
[System.IO.FileMode]::Open
[System.IO.FileAccess]::Read
[System.IO.FileShare]::Read
1024, # Buffer size
[System.IO.FileOptions]::SequentialScan
)
try {
$stream = New-Object System.IO.FileStream -ArgumentList $streamArgs
$metaData = [System.Drawing.Imaging.Metafile]::FromStream($stream)
# get the 'DateTimeOriginal' property (ID = 36867) from the metadata
# Tag Dec TagId Hex TagName Writable Group Notes
# ------- --------- ------- -------- ----- -----
# 36867 0x9003 DateTimeOriginal string ExifIFD (date/time when original image was taken)
# see: https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
# get the date taken as an array of bytes
$exifDateBytes = $metaData.GetPropertyItem(36867).Value
# transform to string, but beware that this string is Null terminated, so cut off the trailing 0 character
$exifDateString = [System.Text.Encoding]::ASCII.GetString($exifDateBytes).TrimEnd("`0")
# return the parsed date
return [datetime]::ParseExact($exifDateString, "yyyy:MM:dd HH:mm:ss", $null)
}
catch{
Write-Warning -Message "Could not read Exif data from '$($FileObject.FullName)'"
}
finally {
If ($metaData) {$metaData.Dispose()}
If ($stream) {$stream.Close()}
}
}
}
使用该函数,您的代码将如下所示:
$Path = 'D:\' # the folder where the jpg files are
$Count = 10 # the starting number. gets increased for each file
# start a loop to gather the files and reset their LastWriteTime property to the one read from the Exif data.
# pipe the result to the Sort-Object cmdlet and enter another ForEach-Object loop to perform the rename.
Get-ChildItem -Path $Path -Filter '*.JPG' -File | ForEach-Object {
$date = $_ | Get-ExifDate
if ($date) {
$_.LastWriteTime = $date
}
$_
} | Sort-Object LastWriteTime | ForEach-Object {
$newName = '{0:00000} {1}.JPG' -f $Count++, ($_.LastWriteTime.toString("dd-MM-yyyy HH.mm"))
# output some info to the console
Write-Host "Renaming file '$($_.Name)' to '$newName'"
$_ | Rename-Item -NewName $newName
}
这使用字符串格式-f
。你给它一个模板字符串,在花括号之间带有编号的占位符。
第一个 {0:00000}
是一种格式化数字的方式,前面有零个字符,在这种情况下最多 5 个字符的长度。
第二个 {1}
被格式化的日期字符串替换。
使用 ++
语法,每次迭代都会增加 $Count
变量。
不使用 ForEach-Object 的 Theo 好答案 (+1) 的替代方法
as Rename-Item
直接接受管道输入。
这需要 -NewName
参数的脚本块,而 $count
需要是 [ref]
(参见来自 mklement0 的
-format operator 允许直接在占位符中应用格式字符串
$Path = 'D:\' # the folder where the jpg files are
$Count = [ref] 10 # the starting number. gets increased for each file
Get-ChildItem -Path $Path -Filter '*.JPG' -File | Sort-Object LastWriteTime |
Rename-Item -NewName {"{0:D5} {1:dd-MM-yyyy HH.mm}{2}" -f `
$Count.Value++,$_.LastWriteTime,$_.Extension} -whatif
如果输出看起来没问题,删除尾随 -WhatIf
参数