首页 > 解决方案 > 如何批量重命名文件,包括数字和修改日期?

问题描述

编辑:我应该选择拍摄日期,因为我们正在处理的照片的修改日期有时会延迟一小时。

我正在尝试编写一些将文件重命名为以下格式的内容:

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"}}

标签: windowspowershellbatch-rename

解决方案


你可以这样做:

$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在每次迭代中都会增加变量。++


推荐阅读