PshellUser
PshellUser

Reputation: 27

Powershell to rename Date Format on file Name

I am trying to work on a powershell to change the DATE + DATE FORMAT on a file name.

 Current FileNames:    
 Accounts_test04262022.csv
 Reports_month04262022.csv
 -------------------
 Goal for file Names:
 Accounts_test2022-04-25.csv
 Reports_month2022-04-25.csv

So powershell will replace the date based on yesterday's date and change the DATE FORMAT. Also the powershell needs to take into consideration the files we receive on Monday, to replace with Friday's date (SKIP Weekend)

What I'm trying to use is :

function Get-PreviousDay {
param(
[datetime] $Date = (Get-Date).Date
)

switch ($Date.DayOfWeek) {
    'Sunday' { $Date.AddDays(-2) }
    'Monday' { $Date.AddDays(-3) }
    Default { $Date.AddDays(-1) }
  }
}

$Rename  = (Get-PreviousWorkday).ToString("yyyy-MM-dd")
$Source = 'C:\bin\Test2\'
Get-ChildItem $Source -filter *.csv | rename-item -NewName `
{$_.name.substring(0,$_.BaseName.length-8) + $_.Extension -replace "?","_$Rename"}

Upvotes: 0

Views: 296

Answers (1)

Try this. I cobbled the comments together to something that works. Please test before using in production.

$file = Get-ChildItem -Path 'C:\Powershell\scripts\' -Filter *.csv -Recurse


foreach ($csv in $file){

$d = Get-Date

if ('Sunday' -contains $d.DayOfWeek) {
  $prevWD = $d.AddDays(-2)}
elseif ('Monday' -contains $d.DayOfWeek ){
  $prevWD = $d.AddDays(-1)
}
else {
  $prevWD = $d.AddDays(-1).DayOfWeek
}

$changeddate = $prevWD = Get-Date -Format 'yyyy-MM-dd'
$finalname = $csv.FullName -replace '\d{8}', ('{0}' -f $changeddate)
Move-Item -Path $csv -Destination $finalname -WhatIf
Write-Verbose -Message ('Changed {0} to {1}' -f $csv, $finalname)

}

output

C:\Powershell\Scripts> . 'C:\Powershell\Scripts\testrename.ps1'
2022-04-26
What if: Performing the operation "Move File" on target "Item: C:\Powershell\Scripts\accounts04042022.csv Destination: C:\Powershell\scripts\accounts2022-04-26.csv".
Changed accounts04042022.csv to C:\Powershell\scripts\accounts2022-04-26.csv
2022-04-26
What if: Performing the operation "Move File" on target "Item: C:\Powershell\Scripts\reports04032022.csv Destination: C:\Powershell\scripts\reports2022-04-26.csv".
Changed reports04032022.csv to C:\Powershell\scripts\reports2022-04-26.csv

Upvotes: 1

Related Questions