0

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

1 Answers1

1

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
SomethingDark
  • 13,229
  • 5
  • 50
  • 55
  • ok so here is my latest version. `del /Q D:\ACT\ACTBKUP FORFILES /P "E:\ACT_Backups" /M *.zip /D +1 /C "cmd copy @files D:\ACT\ACTBKUP"` but the forfiles command is not coping the file. What did I do wrong? – Dennis Hertzler Jun 21 '16 at 18:13
  • 1
    Read the forfiles help output. There is no @files. – ths Jun 21 '16 at 18:26
  • 1
    @DennisHertzler - Also, if you only want the most recent file, you need to adjust your code to what I've shown. – SomethingDark Jun 21 '16 at 18:27
  • @DennisHertzler, besides the missing `/C` option after `cmd` and the wrong variable name `@files` instead of `@file` in your `forfiles` command line, I am pretty sure this is also because of the `/D +1` option; regard that `+1` means _items modified on today's date (day) + 1 or later = items modified tomorrow or later_, so it does not make any sense (unless you have a time machine; this is a stupid design flaw of `forfiles`); I guess you want to refer to _items modified yesterday or later_, right? to achieve that, refer to [this post of mine](http://stackoverflow.com/a/36585535)... – aschipfl Jun 21 '16 at 18:44
  • 1
    I would recommend using `@path` instead of `@file` because you're copying a file between two separate drives. – SomethingDark Jun 21 '16 at 18:45