如何批量重命名文件,包括数字和修改日期?

时间:2019-01-24 15:26:45

标签: windows powershell batch-rename

编辑:我本来应该选择“拍摄日期”,因为我们正在处理的照片有时会“修改日期”缩短一小时。

我正在尝试编写一些东西来将文件重命名为以下格式:

Handler().postDelayed( 1000 ) { doSomething() }

我需要这样做,以便按照父亲设计的方式整理母亲的照片。我专门寻找了首先使用cmd批处理文件执行此操作的方法,但它似乎太复杂了。我现在正在尝试使用PowerShell。

我已经尝试过了,这可行:

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

但是我还没有设法包括一个变量。无法编译:

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

2 个答案:

答案 0 :(得分:5)

您可以执行以下操作:

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

答案 1 :(得分:0)

无需使用ForEach-Object即可替代Theo的好答案(+1)
因为Rename-Item直接接受管道输入。

这需要-NewName参数的脚本块,而$count必须是[ref]
(请参阅来自mklement0的reference

-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参数