Suppose I have a daily date generated CSV file
Eg: File_1_20220321.CSV
How do I use Powershell to change the year to 2015 so the file name would be:
Eg: File_1_20150321.CSV
CodePudding user response:
If you automatically generate the date for the csv-File via
Get-Date -uformat "%m%d%Y"
which is the most logical way to do it for a clean formatting, you can simply add another parameter:
Get-Date -uformat "%m%d%Y" -year "2015"
Hence the way to export your log would be:
$dateold = Get-Date -uformat "%m%d%Y" -year "2015"
Export-Csv -Path "C:\yourpath\filename_$dateold.csv" -InputObject $myobject
CodePudding user response:
To automate the renaming of the file with today's date in its name to have a date 7 years ago, you can do the following:
$today = Get-Date
$filter = '*_{0:yyyyMMdd}.csv' -f $today
Get-ChildItem -Path 'X:\somewhere' -Filter $filter -File |
Rename-Item -NewName { $_.Name -replace "_$($today.Year)", "_$($today.AddYears(-7).Year)"} -WhatIf
I have added safety switch -WhatIf
to the Rename-Item cmdlet.
This makes the command only show in the console what would happen and nothing actually gets renamed. Once you are satisfied the code will rename correctly, remove that -WhatIf
switch and run again.
If the dates in the replacement need to be valid (like when today would be the 29th of Februari and changing the year to 7 years ago, you will end up with an invalid date), use this code:
$today = Get-Date
$todayPattern = '{0:yyyyMMdd}'-f $today
$olderPattern = '{0:yyyyMMdd}'-f $today.AddYears(-7)
$filter = '*_{0:yyyyMMdd}.csv' -f $today
Get-ChildItem -Path 'X:\somewhere' -Filter $filter -File |
Rename-Item -NewName { $_.Name -replace "_$todayPattern", "_$olderPattern"} -WhatIf