Quiero eliminar una carpeta específica en la raíz y los subórdenes, el problema es que mi código solo elimina la carpeta en la raíz del directorio:
SET dirname=test
SET directory=%cd%
SET found=false
if NOT "%1%" == "" (
set directory=%1%
)
echo Searching for %dirname% in %directory%
for /d %%i in (%directory%\%dirname%) do (
IF EXIST %%i (
REM change the sentinel value
set found=true
echo Deleting the folder %%i
REM Delete a folder, even if not empty, and don't prompt for confirmation
RD /s /q %%i
)
)
REM logic to do if no files were found
if NOT "%found%" == "true" (
echo No directories were found with the name of %dirname%
)
Esta es la estructura de carpetas:
E:sampledelete
├───folder1
├───folder2
│ └───somefolder
├───test
│ └───somefolder
├───newfolder
│ ├───test
│ │ └───somefolder
├───newfolder2
│ ├───test
después de ejecutar el script cambió a:
E:sampledelete
├───folder1
├───folder2
│ └───somefolder
├───newfolder
│ ├───test
│ │ └───somefolder
├───newfolder2
│ ├───test
Respuesta1
Los problemas se comentan a continuación. El problema principal fue una idea errónea del directorio: no estaba buscando dentro del directorio debajo de 1 nodo debajo de la raíz. Tuviste la idea correcta. Como eres "nuevo" como dijiste, valdría la pena analizar las diferencias.
@echo off
SET dirname=test
SET directory=%cd%
SET found=false
if NOT "%1%" == "" (
set directory=%1%
)
REM We want to look in the current directory not in for Z:\test
for /d %%i in (%directory%*) do (
echo Searching for %%i\%dirname% in %directory%
REM We already know the folder existed because "do" ran.
REM We want to look beneath the root directory
IF EXIST %%i\%dirname% (
REM change the sentinel value
set found=true
REM we want to delete the nodes beneath not the one in root
echo Deleting the folder %%i\%dirname%
REM Delete a folder
REM we want to delete the nodes beneath not the one in root
RD /s /q %%i\%dirname%
)
IF %%1 == %dirname% (
REM change the sentinel value
set found=true
REM Delete a folder, even if not empty, and don't prompt for confirmation
echo Deleting the folder %%i\%dirname%
RD /s /q %%i
)
)
REM logic to do if no files were found
if NOT "%found%" == "true" (
echo No directories were found with the name of %dirname%
)
Respuesta2
Estás entendiendo mal lo que for /d
hace.
para /d %%i en (directorio 1 archivo 1 directorio 2 archivo 2 directorio 3 archivo 3) hacerdeclaración
hace
SET %%i=dir1
statement
SET %%i=dir2
statement
SET %%i=dir3
statement
El problema es que solo estás diciendo dónde está . Quiere utilizar , que realiza una búsqueda recursiva en el directorio. Tu bucle debería verse asífor /d %%i in (dir1) do statement
dir1
%directory%\%dirname%
for /r
for /r %directory% %%i in (.) do (
if exist %%i\%dirname% (
REM change the sentinel value
set found=true
echo Deleting the folder %%i\%dirname%
REM Delete a folder, even if not empty, and don't prompt for confirmation
RD /s /q %%i\%dirname%
)
)