根据文件日期的部分将一堆文件重命名为一系列日期?

时间:2017-02-02 23:46:28

标签: powershell

我有一个包含几百个文件的文件夹。它们被命名为

  • file.001.txt
  • file.002.txt
  • file.003.txt
  • ...
  • file.223.txt

我尝试使用以下逻辑编写一个powershell脚本来重命名它们。关键日期。说2015年1月1日。然后根据文件名末尾的索引号迭代该日期。所以你最终得到:

  • file.01.02.2015.txt
  • file.01.03.2015.txt
  • file.01.04.2015.txt
  • ...
  • file.08.12.2015.txt

代码示例我已经剔除了,但不知道如何表达这一点。

Get-ChildItem "C:\MyFiles" -Filter
*.txt |  Foreach-Object {
    $OldName = $_.name;
    $IndexPortion = $_.name.Substring(6,3)
    $DatePortion = [datetime]::ParseExact('01/01/2015','MM/dd/yyyy',$null).AddDays($IndexPortion)
    ## ??? $NewName = $_.name -replace $IndexPortion, $DatePortion -format yyyy.MM.dd
    Rename-Item -Newname $NewName;
    Write-Output $("Renamed {0} to {1}" -f $OldName, $NewName)
} 

2 个答案:

答案 0 :(得分:4)

Get-ChildItem *.txt | Rename-Item -NewName { 
    $num = $_.Name.Split('.')[-2]
    $_.Name -replace $num, (Get-Date '2015-01-01').AddDays($num).ToString('MM-dd-yyyy') 
} -whatif

What if: Performing the operation "Rename File" on target "Item: D:\t\file.001.txt Destination: D:\t\file.01-02-2015.txt".
What if: Performing the operation "Rename File" on target "Item: D:\t\file.002.txt Destination: D:\t\file.01-03-2015.txt".
What if: Performing the operation "Rename File" on target "Item: D:\t\file.003.txt Destination: D:\t\file.01-04-2015.txt".

如果数字不在文件名(file 001 test.001.txt

中的其他位置,这应该有用

你不能让你的代码放Rename-Item -Newname $NewName;而不说要重命名的文件,你可以将文件传递到Rename-Item并使用scriptblock计算新名称,因此不需要循环

如何进行日期计算可能会有所不同,但我选择将文件拆分为圆点并使用倒数第二个条目和固定字符串中的Get-Date。你的ParseExact方法看起来也很合理。

答案 1 :(得分:1)

此模式可以让您解决问题。根据需要进行调整。

<强> CODE

$inputs = @()
$inputs += 'file.001.txt'
$inputs += 'file.002.txt'
$inputs += 'file.100.txt'
$inputs += 'file.234.txt'
$inputs += 'file.1234.txt'

$epoch = [DateTime]::Parse("1/1/2015")
$inputs | % {
    $oldName = $_
    $pre, $id, $post = $oldName -split '\.'
    $newDate = $epoch.AddDays($id)
    $newId = $newDate.ToString("MM.dd.yyyy")
    $newName = "{0}.{1}.{2}" -f $pre, $newId, $post

    Write-Output "$oldName ==> $newName"
}

<强>输出

file.001.txt ==> file.01.02.2015.txt
file.002.txt ==> file.01.03.2015.txt
file.100.txt ==> file.04.11.2015.txt
file.234.txt ==> file.08.23.2015.txt
file.1234.txt ==> file.05.19.2018.txt