I'm currently in the process of writing a simple batch file. I'm not new to programming, but by no means an expert. This is the first time I've used batch files.
Basically I want a file from one directory to be moved to another, and, if there is already a file with the same name in the target directory, it will rename it as a backup. This way it will always keep a backup in case this script is accidentally run.
After hours of troubleshooting my code, I still don't know why It doesn't work. I suspect it's something to do with nested if statements. An If statement inside an if statement (for a lack of a better explanation).
I would appreciate the help. Thanks
@echo off
REM Variables
rem dir1 is the source directory
set dir1=C:\Users\%username%\Desktop\Dir1\
rem dir2 is the target directory
set dir2=C:\Users\%username%\Desktop\Dir2\
rem file is the name of the source file and desired name of the target file
set file=file.txt
rem pre1 is the name of the copy of the old target file before it is overwritten
set pre1=push backup
rem pre2 is the name of prefix for a temporary file created in the target directory
set pre2=temp
REM if source file exist
if exist %dir1%%file% (
rem if there is a file named the same in target directory
if exist %dir2%%file% (
rem if there is allready a backup file
if exist %dir2%%pre1%%file% (
rem rename the backup file as a temp file
rename %dir2%%pre1%%file% %dir2%%pre2%%file%
rem rename the old file as backup file
rename %dir2%%file% %dir2%%pre1%%file%
rem move source file to target directory
move %dir1%%file% %dir2%
rem if rename failed
if not exist %dir2%%file% (
rem rename the backup to the normal file
rename %dir2%%pre1%%file% %file%
rem rename the temp file to the backup file
rename %dir2%%pre2%%file% %pre1%%file%
rem echo error
echo rename error
pause
rem Delete temp file
) else ( del %dir2%%pre2%%file% )
)
) ELSE ( move %dir1%%file% %dir2% )
) ELSE ( echo %file% does not exist in directory "%dir1%" )
pause
Apologies for my sloppy commenting.
Aucun commentaire:
Enregistrer un commentaire