【问题标题】:Rename a bunch of files to series of dates based on portion of file date?根据文件日期的一部分将一堆文件重命名为一系列日期?
【发布时间】:2017-02-02 23:46:27
【问题描述】:

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

  • 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)
} 

【问题讨论】:

    标签: powershell


    【解决方案1】:
    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 并使用脚本块计算新名称,因此无需循环。

    如何进行日期计算可能会有所不同,但我将文件拆分为点并获取倒数第二个条目,并从固定字符串中获取日期。您的 ParseExact 方法看起来也很明智。

    【讨论】:

    • 这就像一个魅力谢谢。如果进行各种类型转换等,我会迷路。这就是我来自 C# 背景的原因。
    【解决方案2】:

    这个模式应该可以让你解决你的问题。根据需要进行调整以满足您的需要。

    代码

    $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
    

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多