在每个文件中使用特定字符串重命名目录中的多个文件



我有一个包含多个文件的文件夹,需要将它们重命名为文件夹内的字符串。字符串是交互的日期。

当前文件命名为

AUDIT-1.log
AUDIT-2.log
AUDIT-3.log

ect . .

我需要将它们设为

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:TestTempAUDIT-2.LOG

每个文件只有一个日期。

下面是我当前的代码:

$dir ="C:TestTemp"
$files = Get-ChildItem -Path "$dir*.log"
$RegexDate = 'dd/dd/dd'
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 }
}

正如Santiago Squarzon在评论中指出的那样,直接的解决方案是将$files交换为$file。为了代码简洁,这里有一个您可以实现的单一管道解决方案来获得相同的结果:

Select-String -Path "$dir*.log" -Pattern '(d+/){2}d+' | 
Rename-Item -NewName { 
$_.FileName -replace '-', "-$($_.Matches.Value.Replace('/','-'))-" 
} -WhatIf

再次,正如在评论中提到的,使用Select-String允许读取文件,这提供了通过参数绑定通过其Path属性直接管道到Rename-Item的机会。因此,使用scriptblock进行新名称替换,我们实际上是将从模式匹配中找到的插入到-所在的文件名中。


-WhatIf安全/通用参数可以在您指定这些是您所追求的结果时删除。

这将使用文件的最后写入时间重命名文件。如果文件已经是该格式,则不会重命名它们。有一个哈希表用于跟踪文件日期后缀的增量。这样,文件就可以按日期组织。

$dir = "C:TestTemp"
$files = Get-ChildItem -Path "$dir*.log"

#Hashtable to track the suffix for the files
[hashtable]$dateTracking = @{}
#Using padding to format the suffix with two digits, in case there more then 9 files
#incrase it if you have more then 99 files per day increase padding
$suffixPadding = '{0:d2}'
foreach ($file in $files) {
#Don't rename files that were already renamed
if ($file.Name -notmatch "AUDIT-d{2}-d{2}-d{2}-d{2}.log") {
$date = $file.LastWriteTime.ToString("MM-yy-dd")
#If the date is not entered in the hashtable add it with suffix 01
if (-not $dateTracking.ContainsKey($date)) {        
$dateTracking.Add($date, $suffixPadding -f 1)
}
#Else increment suffix
else {
$dateTracking[$date] = $suffixPadding -f ([int]$dateTracking[$date] + 1)
}
#Here we use the date in the name of the file and getting the suffix from the hashtable
Write-Host "Renaming $($file.Name) to AUDIT-$date-$($dateTracking[$date]).log"
Rename-Item -Path $file -NewName "AUDIT-$date-$($dateTracking[$date]).log"
}
}

最新更新