[英]Replace Part of a File Name in Powershell
I have files that look like this:我有看起来像这样的文件:
2020-0517-example.pdf 2020-0517-example.pdf
2020-0412-example.pdf 2020-0412-example.pdf
2020-0607-example.pdf 2020-0607-example.pdf
I would like to rename the files to:我想将文件重命名为:
2020-0723-example.pdf 2020-0723-example.pdf
2020-0723-example.pdf 2020-0723-example.pdf
2020-0723-example.pdf 2020-0723-example.pdf
I would basically be replacing the dates to today's date while keeping the year and the suffix.我基本上会将日期替换为今天的日期,同时保留年份和后缀。
If you want to add a bit of sanity checking to make sure you are dealing with dates, you can use pattern matching and then rename the partial date:如果您想添加一些完整性检查以确保您正在处理日期,您可以使用模式匹配,然后重命名部分日期:
$date = Get-Date -Format MMdd
Get-ChildItem -Path <filepath> -File |
Where Basename -match '^(?:19|20)\d\d-(?:0[1-9]|1[012])\d\d-' |
Rename-Item -NewName { $_.Name -replace '(?<=^\d{4}-)\d{4}',$date } -whatif
Alternatively, you can parse the date string first to verify it using TryParseExact
:或者,您可以先解析日期字符串以使用TryParseExact
进行验证:
$date = Get-Date -Format MMdd
Get-ChildItem -Path <filepath> -File |
Where Name -match '^\d{4}-\d{4}-' | Foreach-Object {
if ([datetime]::TryParseExact($_.Name.Substring(0,9),'yyyy-MMdd',[System.Globalization.CultureInfo]::InvariantCulture,[System.Globalization.DateTimeStyles]::None,[ref]0)) {
$FileParts = $_.Name -split '-',3
Rename-Item -Path $_ -NewName ($FileParts[0],$date,$FileParts[2] -join '-') -WhatIf
}
}
You will need to remove the -WhatIf
parameter for the rename operation to complete.您需要删除-WhatIf
参数才能完成重命名操作。
Explanation:解释:
Using -split '-',3
, we ensure that we are left with no more than three array elements.使用-split '-',3
,我们确保剩下的数组元素不超过三个。 This provides a predictable number of indexes for putting the file name back together.这为将文件名重新组合在一起提供了可预测数量的索引。 [0]
will be the year. [0]
将是年份。 [1]
will be the month-day. [1]
将是月日。 [2]
will be the remainder of the file name. [2]
将是文件名的其余部分。
Please see the following for the -replace
and -match
regex details:有关-replace
和-match
正则表达式的详细信息,请参阅以下内容:
You could split by "-"
and stitch together with String.Format
:您可以用"-"
分割并与String.Format
缝合在一起:
$filename = "2020-0517-example.pdf"
$today = Get-Date
$arr = $filename.Split("-")
$newname = "{0}-{1:MMdd}-{2}" -f $arr[0], $today, $arr[2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.