Szarekh
Szarekh

Reputation: 1

Rearranging parts of a date in a filename using powershell

I want to rename

backup_01_03_2020__.log

to

backup_2020_01_03__.log

I have tried reading about powershell but not found anything useful, since i don't have good knowledge about powershell.

Any suggestions or good link to some material much appreciated

Upvotes: 0

Views: 187

Answers (3)

js2010
js2010

Reputation: 27423

Here's a non-regex approach. Are there really two _'s before .log?

echo hi > backup_01_03_2020__.log

dir *_*_*_*__.log | rename-item -newname { 
  ($_.name -split '_')[0,3,1,2,4,5] -join '_' } -whatif

What if: Performing the operation "Rename File" on target "Item:
/Users/js/foo/backup_01_03_2020__.log Destination: 
/Users/js/foo/backup_2020_01_03__.log".

Upvotes: 0

Theo
Theo

Reputation: 61068

Using the -Filter will pre-filter the files to fetch on a simple pattern. Next, pipe the remaining results to a Where-Object clause to be able to use the regex -match operator.

All files that match that can be renamed using a scriptblick as -NewName parameter like this:

# you might want to add switch '-Recurse' if you have logs to rename in subfolders
Get-ChildItem -Path 'X:\Logs' -Filter 'backup_*.log' -File |   
    Where-Object { $_.BaseName -match '^backup_(\d{2})_(\d{2})_(\d{4})' } |
    Rename-Item -NewName { 'backup_{0}_{1}_{2}__.log' -f $Matches[3], $Matches[1], $Matches[2] } -WhatIf

Remove the -WhatIf switch if the output from the console shows you the correct new file names

Result:

X:\Logs\backup_01_03_2020__.log  -->  X:\Logs\backup_2020_01_03__.log
X:\Logs\backup_01_07_2020__.log  -->  X:\Logs\backup_2020_01_07__.log

Upvotes: 0

stackprotector
stackprotector

Reputation: 13442

I recommend using a regular expression with groups to capture each part of the date individually. You can then create a new name by rearranging each part of the date:

$files = Get-ChildItem -Path C:\path\to\logs\* -Include *.log
foreach ($file in $files) {
    if ($file.Name -match 'backup_(\d{2})_(\d{2})_(\d{4})__\.log') {
        Rename-Item -Path $file -NewName "backup_$($Matches[3])_$($Matches[1])_$($Matches[2])__.log"
    } else {
        Write-Host "'$($file.Name)' does not match the pattern!"
    }
}

Upvotes: 1

Related Questions