Delete all folders except.... (*.BAT)
Asked Answered
L

3

4

I would like to delete all folders except MYFOLDER found in a parent directory but I cant get it done?

for %%i in ("C:\Parent") do if not "%%i"=="MYFOLDER" del /f /q "%%i

could somebody please check the code?

(I'm using *.bat)

Leena answered 10/1, 2014 at 15:48 Comment(2)
Please check social.technet.microsoft.com/Forums/scriptcenter/en-US/…Procedure
Do you like to delete files or folders? If you want to delete folders, should use RD instead DEL.Nationalism
L
4

This should help you:

for /d %%i in ("C:\Parent\*") do if /i not "%%~nxi"=="MYFOLDER" del /s /q "%%i"
Lynettalynette answered 11/1, 2014 at 0:51 Comment(2)
Can you explain what %%~nxi stands for? It doesn't work for me, but %%i does.Adlai
rd for folder i guess.Repp
P
0

Dir all folders and check one by one if it is not MYFOLDER, if is not - delete it. Please remove echo when running the real job.

for /d %%i in (C:\Parent\*) do (
    if /i "%%i" NEQ ".exe" echo rd /S /Q %%i
)
Procedure answered 10/1, 2014 at 18:24 Comment(2)
Note that you spare yourself a lot of pain if you just use for /d instead of iterating over dir output with for /f.Neuburger
Yeah, sorry, should be /F.Procedure
O
0

Or simply copy MYFOLDER to a temp folder, delete all files, and copy back MYFOLDER. Unless MYFOLDER is huge and takes time to copy, this should work just as good.

Otto answered 6/3, 2015 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.