How to delete files in a directory with batch script?

Asked

Viewed 13,268 times

3

I need that when executing one script cmd. it erases all files with the following extensions: .txt and .mp4 if any. These files are located in the following folder C:\comando\batch\diretorio\teste and the script cmd. is located in C:\comando\batch.

How could I do that, knowing that after these commands, others will be executed, but not to the folder test, and yes in the folder batch.

That is, it is possible to do this without leaving the folder batch?

Commands must be compatible with Windows 2003/XP.

2 answers

4


It is possible yes. To delete files, use del.

If you prefer to delete files using the absolute path, use the variable %~dp0 to obtain the folder of script and indicate the target subfolder.

You can iterate on a array with extensions and use joker to match files with certain extensions.

@echo off

set "subpasta=%~dp0%diretorio\teste\" REM a pasta do batch e subpasta
set "extensoes=txt mp4"               REM separe as extensoes com espaco

for %%i in (%extensoes%) do (
    echo Deletando arquivos do tipo %%i da pasta %subpasta%
    del %subpasta%*.%%i
)

if %errorlevel% EQU 0 (
    echo Operacao realizada com sucesso
) else (
    echo Nao foi possivel deletar um ou mais arquivos
)

Obs: To show no output, you redirect the stdout and stderr for null thus: del %subpasta%*.%%i 2> nul

  • Just a doubt, the way it is there, no confirmation is needed when executing the del right? Or you have to put the /q as mentioned in the comments? If yes, how would it be? ps: I liked the command %~dp0 very interesting :)

  • 1

    @Florida As far as I know not, but if you want you can use the /p to ask before. About the %~dp0, https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

3

Since it is a subfolder of your root directory, not the need to quit, but I in particular always prefer to use the command with an absolute path for greater security.

del C:\comando\batch\diretorio\teste\*.txt /s

del C:\comando\batch\diretorio\teste\*.mp4 /s

/s deletes recursively.

ex: inside the folder have another folder(test/videos) with mp4 files, they will also be deleted.

So you can continue your routine!

  • I think /s is to delete files from as recursive, see here. To ignore the questions, it must be /q.

  • That’s right @stderr, thanks for the remark.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.