Rename .bak file to include date that was 7 days in the past

时间:2016-03-02 10:56:09

标签: batch-file

You'll have to forgive me as I am a beginner when it comes to batch file and Powershell scripting.

We have a backup solution with SQL that is currently being tested, which will perform Full backups once a week and then Differental backups for the reminder of the weekdays. As part of the restore process, we have a Windows batch script file in place which will rename the Full backup file before compressing it with 7Zip. The rename portion of the script looks like this:

cd C:\SQL Backups\Production Backups\eStart_Good
set date=%date:~-4%_%date:~3,2%_%date:~0,2%
ren *%date%* eStart_Good_FullBackup.bak

As this command will get run once a week on the night of a Full backup, it looks for today's date in the form of eg. 2016_03_02 because that's how the naming convention is set when backing up from SQL. This works as it should do.

However, what I want to happen after a Full backup from SQL as occurred is rename the previous eStart_Good_FullBackup file by taking out the 'FullBackup' portion of the name and replace with the date 7 days previous to today's date. So if the next Full backup is set to run on 04/03/2016, I want it to show up in the file name as 2016_02_26 for example.

I know with the rename command I need to change it to:

ren FullBackup eStart_Good_%date%.bak (FullBackup being a wild card.)

But, I've tried a number of combinations to change the set date variable and I keep getting the wrong numbers or pieces of code when echoing the variable.

set date=%date:~-4%_%date:~3,2%_%date:~0,2%

Does anyone have any advice they can give me please?

1 个答案:

答案 0 :(得分:0)

在批处理脚本中处理日期很复杂。 Powershell可能是更简单的方式来使用它。但是,有时Powershell不是一个选项,您只需要使用批处理脚本。这是我写的一个脚本,用于了解昨天':How do I find last Sunday's date and save it in a variable in a Windows batch file。七天前你可以循环七次。

希望这有帮助。