关于powershell:通过重新格式化文件名称中嵌入的日期字符串来重命名文件

Rename files by reformatting the date string embedded in their names

我正在CMD中使用Windows的Powershell从我的文件名中删除"星期一,星期二,星期三"等,效果很好

1
2
3
4
5
6
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Mon","") }
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Tue","") }
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Wed","") }
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Thur","") }
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Fri","") }
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace("Sat","") }

现在我的文件名看起来像这样:
2018年7月13日-Lorem ipsum

我想用月份切换日期,所以它将是:
2018年7月13日,所以我可以按月对其进行排序。甚至是2018年7月13日。

我该怎么做?

谢谢,
迈克


您可以使用Rename-Item和延迟绑定脚本块将两个所需的转换合并为一个操作,其中-replace运算符允许您根据正则表达式(正则表达式)根据需要转换文件名。铅>

1
2
3
Get-ChildItem -Recurse -Name | Rename-Item -NewName {
  $_.Name -replace '\\w+ (\\d+) (\\w+) (\\d+)', '$3 $2 $1'
} -WhatIf

-WhatIf预览重命名操作;删除它以执行实际的重命名。

例如,名为Mon 13 July 2018 - Lorem ipsum的输入文件将重命名为2018 July 13 - Lorem ipsum

注意:此示例文件名碰巧没有文件扩展名,但是上面和下面的解决方案都可以使用具有扩展名的文件名。

有关PowerShell的-replace运算符的更多信息,请参见此答案。

如果要使用诸如2018-07-13之类的嵌入式格式使文件名真正可排序,以表示13 July 2018,则需要通过-split运算符进行更多的工作:

1
2
3
4
5
6
7
8
Get-ChildItem -Recurse -Name | Rename-Item -NewName {
  # Split the name into the date part (ignoring the weekday) and the
  # rest of the file name.
  $null, $date, $rest = $_.Name -split '\\w+ (\\d+ \\w+ \\d+)'
  # Convert the date string to [datetime] instance, reformat it, and
  # append the rest.
  ([datetime] $date).ToString('yyyy-MM-dd') + $rest
} -WhatIf

例如,名为Mon 13 July 2018 - Lorem ipsum的输入文件将重命名为2018-07-13 - Lorem ipsum

有关PowerShell的-split运算符的更多信息,请参见此答案。
帮助主题about_Assignment_Operators

中介绍了分配给多个变量($null, $date, $rest = ...)


不是您的问题的答案,IMO mklement0的答案最有效。

但是代替了 ugly 次优示例代码。

基于RegEx的-replace运算符优于.replace()方法
当有替换替换时。

1
[Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames

返回当前语言环境的缩写天名称,可以将其组合
在一个RegEx "(Sun|Mon|Tue|Wed|Thu|Fri|Sat)"中,代码为

1
2
3
$RE=[regex]"("+([Globalization.DatetimeFormatInfo]::CurrentInfo.AbbreviatedDayNames -join '|')+")"

Get-ChildItem -recurse -File | Rename-Item -NewName {$_.Name -replace $RE} -WhatIf

不需要使用-replace运算符来表示空的替换字符串。

如果输出看起来不错,请删除结尾的-WhatIf


您可以使用以下代码转换日期

1
2
3
$string = '13 July 2018 - Lorem ipsum'
$dateObject = [datetime]$string.Split('-')[0]
Write-Output"$($dateObject.ToString('yyyy MMMM dd')) - $($array[1])"

这将输出

1
2018 July 13 -  Lorem ipsum

您可以将每个月的替换链接起来,并以replace语句结尾来切换这样的数字

1
2
3
4
"13 July 2018 - Lorem ipsum" `
    -replace 'July', '07' `
    -replace 'Aug', '08' `
    -replace"(\\d+) (\\d+) (\\d+)", '$3 $2 $1'

夹心返回

1
2018 07 13 - Lorem ipsum