开发者

Batch Script issue

for deleting files, I will be using the code below to remove the oldest file in the directory and run it every day. It came from the question of mine.

Applying to the original batch script:

SET BACKUPDIR=C:\PATH\TO\BACKUPS
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%

Something such as that checks if the file amount is 21, if so delete the latest one:

SET BACKUPDIR=C:\test
SET countfiles = dir BACKUPDIR /b | find /v /c "::"

if countfiles > 21
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO开发者_如何学Python SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%

EDIT: Sorry for forgetting the question, my attempt was failing, I would be greatful for any way to direct how to make it work.


first, it seems set does not like spaces between the variable and the = sign: if you put a space, the variable name will include a space. so you must remove the space to properly define the variable name.

plus, your syntax for capturing the output of the command into a variable is wrong. the only way i am aware of (after desperately searching stackoverflow for the answer) is to use a for loop trick to use a temporary variable (see this question for more details). actually, you also need to escape the pipe for the command to be parsed correctly.

then, when the variable tested in the if expression does not exists, the results is always true, so make sure the variable exists. by removing the space as said above, the name in the if expression will match your variable name, and the test will execute properly.

then you forgot to make a block around the 2 last commands. actually, you are testing if you have more than 21 files and compute the oldest if it is true, then you ALWAYS delete the oldest.

also, the greater than operator > may be understood as a redirection. you may need to use the GTR operator.

SET BACKUPDIR=C:\test
FOR /F %%i in ('dir BACKUPDIR /b ^| find /v /c "::"') DO SET countfiles=%%i

if countfiles GTR 21 (
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%
)


That's not working...you can't set 'normal' variables within a for-loop. I had the same problem some days ago and solved it with this blog entry.

Basically, you need to set SETLOCAL ENABLEDELAYEDEXPANSION and then use ! instead of %...

set FILES=
for /f %%a IN (‘dir /b *.txt’) do set FILES=!FILES! %%a
echo %FILES%

So, this should work for you:

SETLOCAL ENABLEDELAYEDEXPANSION
SET OLDEST=
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜