Search code examples
regexpowershellrename

Renaming multiple files in directory using a specific string in each file


I have a folder with multiple files and need to rename them to a string inside of the folder. The string is the date of interaction.

Currently the files are named as

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

ect..

I need to have them as

AUDIT-11-08-22-1.log
AUDIT-11-07-22-2.log
AUDIT-11-08-22-3.log

The issue I am having with the current iteration of the code, the dates of all files are collected and it attempts to rename the file with all dates

EXAMPLE:

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

There is only one date in each file.

The following is my current code:

$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 }

}

Solution

  • As pointed out in the comments by Santiago Squarzon, the immediate fix is to swap $files, for $file. For code brevity, here's a single pipeline solution you can implement to attain the same results:

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

    Again, as mentioned in the comments, the use of Select-String allows the reading of file(s) presenting the opportunity to pipe directly into Rename-Item via parameter binding through its Path property. So, using a scriptblock for the new name replacement we're essentially inserting the value found from it's pattern matched into the file name where - would have been.


    The -WhatIf safety/common parameter can be removed when you've dictated those are the results you are after.