Search code examples
batch-filewindows-server-2012-r2

Why is my bat script deleting itself when I run it


I have made a bat script as follows

cd "D:\ACT\ACTBKUP"
del /Q *.* 

FORFILES /P E:\ACT_Backups /M *.zip /D +1 /C "cmd /c del @D:\ACT\ACTBKUP"

The script is supposed to delete everything in "D:\ACT\ACTBKUP" and then move the newest zip folder to that same folder from E:\ACT_Backups. When I run this script from windows server 2012 it just disappears.

thanks


Solution

  • In order to switch to a directory that is located on a different drive, you need to use cd /d instead of just cd. If you do not do this, the directory will not change.

    When you run a script by double-clicking on it, batch considers the current directory to be the directory where the script is currently located. Since you are not using the /d option with cd, you are running del /Q *.* on the directory where the script is located.

    To fix this, you have two options:

    cd /d "D:\ACT\ACTBKUP"
    del /Q *.*
    

    or

    del /Q "D:\ACT\ACTBKUP"
    


    There is no option in forfiles to get just the most recent file; /D +1 will return all files with a last-modified date of today or later. In order to get the most recent file and nothing else, you will need a for /f loop:

    rem /b returns just the file name and /o:d sorts the files by date
    rem Since newest_file gets set for each .zip file in the directory,
    rem the last file set will be the newest
    for /f "delims=" %%A in ('dir /b /o:d E:\ACT_Backups\*.zip') do set newest_file=%%A
    copy %newest_file% D:\ACT\ACTBKUP