我有一个包含多个文件的文件夹,需要在文件夹内将它们重命名为字符串。字符串是交互的日期。
当前文件命名为
AUDIT-1.log
AUDIT-2.log
AUDIT-3.log
等等
我需要他们
AUDIT-11-08-22-1.log
AUDIT-11-07-22-2.log
AUDIT-11-08-22-3.log
我在当前代码迭代中遇到的问题是,收集所有文件的日期,并尝试使用所有日期重命名文件
示例:
NewName: 11-08-22 11-07-22 11-06-22 11-09-22 11-08-22 11-07-22 11-06-22 11-09-22-1.LOG
OldName: C:\TestTemp\AUDIT-2.LOG
每个文件中只有一个日期。
以下是我当前的代码:
$dir ="C:\TestTemp"
$files = Get-ChildItem -Path "$dir\*.log"
$RegexDate = '\d\d\/\d\d\/\d\d'
Measure-Command{
$file_map = @()
foreach ($file in $files) {
$DateName= Get-Content $files |
Select-String $RegexDate |
foreach-object { $_.Matches.Value } |
Select-Object
$NewDateName= $DateName.replace('/','-')
$b = 1
$file_map += @{
OldName = $file.Fullname
NewName = "$NewDateName-$b.LOG" -f $(Get-Content $file.Fullname | Select-Object $NewDateName.Fullname)
}
}
$file_map | ForEach-Object { Rename-Item -Path $_.OldName -NewName $_.NewName }
}
2条答案
按热度按时间avwztpqn1#
正如Santiago Squarzon在注解中指出的,立即解决的方法是用
$files
替换$file
。为了代码简洁,可以实现以下单管道解决方案来获得相同的结果:同样,正如在注解中提到的,使用
Select-String
允许阅读文件,这提供了通过Path
属性的 * 参数绑定 * 直接管道传输到Rename-Item
的机会。因此,使用脚本块进行新名称替换实际上是将从模式匹配中找到的值 * 插入 * 到-
所在的文件名中。-WhatIf
安全/通用参数。*dhxwm5r42#
这将使用文件的最后一次写入时间来重命名文件。如果文件已经是该格式,则不会重命名。有一个哈希表来跟踪文件日期后缀的增量。这样,文件就可以按日期进行组织。