Delete all folders in a folder except two

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tbharber
Posts: 32
Joined: 17 Sep 2010 17:08

Delete all folders in a folder except two

#1 Post by tbharber » 06 Oct 2010 10:19

I am writing a script that will remove all of the user accounts on a computer. Currently the code is:
rmdir /s /q "\\%computername%\c$\Documents and Settings\"

This removes all folders (user windows profiles) under the documents and settings folder. The problem is this also removes the "All Users" folder and the "Default User" folders as well. I need a way to remove all other folders than these two folders. The user ID's for each computer will vary so it wont be as simple as just deleting specific folders.

Any thoughts?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Delete all folders in a folder except two

#2 Post by aGerman » 06 Oct 2010 15:16

You could try this

Code: Select all

@echo off &setlocal
pushd "\\%computername%\c$\Documents and Settings\" ||goto :eof
for /f "delims=" %%a in ('dir /ad /b ^| findstr /b /i /v /c:"all users" ^| findstr /b /i /v /c:"default user"') do (
  ECHO rmdir /s /q "%%a"
)
popd
pause

If you think it would work, then remove the ECHO command to do the job.

Regards
aGerman

amel27
Expert
Posts: 177
Joined: 04 Jun 2010 20:05
Location: Russia

Re: Delete all folders in a folder except two

#3 Post by amel27 » 06 Oct 2010 17:53

aGerman wrote:'dir /ad /b ^| findstr /b /i /v /c:"all users" ^| findstr /b /i /v /c:"default user"'

this block may be shorter, and hidden folders (LocalService, NetworkService) must be exclude:

Code: Select all

'dir /ad-h/b^| findstr /xivc:"all users" /c:"default user"'

Post Reply