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 }
}
Get-Content $files? it should be$file. AlsoSelect-Stringcan read files ;) no need toGet-ContentSelect-String -Path "$dir\*.log" -Pattern '(\d+\/){2}\d+' | Rename-Item -NewName { $1,$2 = $_.FileName -split '-'; "$1-" + $_.Matches.Value.Replace('/','-') + "-$2" } -WhatIf