Reputation: 23
I have difficulties creating a batch file or a single Windows command line to delete all files and folders excluding the parent and the first children.
I have for example a folder Test
having 4 more folders:
What I want is to delete everything inside Folder_1
to Folder_4
, but keep the folders themselves. (Test/Folder_1
-> Test/Folder_4
)
I know how to delete everything inside a parent, but I can't figure it out how to go one layer deeper for running the command in every folder I want to keep:
del /q "C:\Temp\Test\*"
FOR /D %%p IN ("C:\Temp\Test\*.*") DO rmdir "%%p" /s /q
Upvotes: 1
Views: 2001
Reputation: 49167
This batch file can be used to delete all files in C:\Temp\Test
as well as all files and subfolders in the folders of C:\Temp\Test
.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "BaseFolder=C:\Temp\Test"
if not exist "%BaseFolder%\" goto :EOF
del /A /F /Q "%BaseFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%BaseFolder%" /AD /B 2^>nul') do pushd "%BaseFolder%\%%I" 2>nul && ( rd /Q /S "%BaseFolder%\%%I" 2>nul & popd )
endlocal
This batch file deletes also files with hidden and read-only attribute and works also for hidden folders in C:\Temp\Test
.
Please read answer on How to delete files/subfolders in a specific directory at command prompt in Windows for a full explanation on how the two command lines deleting files and folders work.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
popd /?
pushd /?
rd /?
set /?
setlocal /?
Upvotes: 1
Reputation: 16266
If you wanted to do this with PowerShell, it might be easier for someone to understand later. Yes, the .bat for loops work. This seems to convey what is being done more directly to me.
[cmdletbinding()]
Param()
Get-ChildItem -Path './test' -Recurse -Directory |
ForEach-Object {
Write-Verbose "working on $_"
Remove-Item -Path $_.FullName -Recurse
mkdir $_.FullName | Out-Null
}
If you want to run this from a cmd.exe prompt, put the code above into a file such as delsubs.ps1 and run it with the following.
powershell -NoProfile -File delsubs.ps1
Upvotes: 0