为什么我的 bat 脚本会在我 运行 时自行删除

Why is my bat script deleting itself when I run it

我做了一个bat脚本如下

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

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

该脚本应该删除 "D:\ACT\ACTBKUP" 中的所有内容,然后将最新的 zip 文件夹移动到 E:\ACT_Backups 中的同一文件夹。当我 运行 来自 windows 服务器 2012 的这个脚本时,它就消失了。

谢谢

为了切换到位于不同驱动器上的目录,您需要使用 cd /d 而不是 cd。如果不这样做,目录将不会改变。

当您 运行 双击脚本时,批处理会将当前目录视为脚本当前所在的目录。由于您没有将 /d 选项与 cd 一起使用,因此您正在 运行ning del /Q *.* 脚本所在的目录。

要解决此问题,您有两种选择:

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

del /Q "D:\ACT\ACTBKUP"


forfiles 中没有仅获取最新文件的选项; /D +1 将 return 所有最后修改日期为今天或更晚的文件。为了得到最新的文件而不是别的,你需要一个 for /f 循环:

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