How to delete files in a directory with batch script?

2

I need to run a script.cmd to delete all files with the following extensions: .txt and .mp4 if they exist. These files are located in the following C:\comando\batch\diretorio\teste folder and script.cmd is located at C:\comando\batch .

How can I do this, knowing that after these commands, others will be executed, but not to the test folder, but rather to the batch folder.

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

Commands must be compatible with Windows 2003 / XP.

    
asked by anonymous 23.10.2016 / 06:16

2 answers

3

Yes, it is possible. To delete the files, use del .

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

You can iterate over array with extensions and use wildcard 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
)

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

23.10.2016 / 12:12
0

As it is a sub folder of your root directory, not the need to exit, but I particularly prefer to always 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

The '/ s' recursively deletes.

Eg, inside the folder has another folder (test / videos) with mp4 files, they will also be erased.

Dai you can continue with your routines!

    
23.10.2016 / 07:33