2017-02-02 13 views
0

我有一个包含几百个文件的文件夹。它们被命名为将一堆文件重命名为基于文件日期部分的一系列日期?

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

我正在尝试编写一个PowerShell脚本,用以下逻辑重新命名它们。取一个关键日期。说1/1/2015。然后根据文件名末尾的索引号迭代该日期。所以,你最终用:

  • file.01.02.2015.txt
  • file.01.03.2015.txt
  • file.01.04.2015.txt
  • ...
  • 文件。 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) 
} 

回答

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计算新名称,因此不需要循环。

如何做日期计算可能会有所不同,但我去分割点上的文件,并采取倒数第二项,并从固定字符串获取日期。您的ParseExact方法也非常明智。

+0

这工作了魅力的感谢状。如果进行各种类型的转换等,我会迷路。这就是我从C#背景得到的结果。 – RThomas

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

谢谢,总是很高兴看到其他方法 – RThomas

相关问题