Reputation: 14053
I want to delete files and folder in a directory excluding some file and folder in a bat file.
I need to keep these file, update.bat FolderName.zip FolderName
and all other should deleted from the directory,
I wrote the .bat file but seems FolderName
also get deleted from directory, rest working fine.
Can anyone tell what wrong with below script?
attrib +r update.bat
attrib +r FolderName.zip
attrib +r FolderName
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
attrib -r update.bat
attrib -r FolderName.zip
attrib -r FolderName
Thanks Haris
Upvotes: 1
Views: 2131
Reputation: 61
you can try to using TotalCommander with Synchronize Dirs options, make one empty folder for Synchronize.
Upvotes: -1
Reputation: 70961
While it is usually used to copy files, with a proper setup robocopy
can also handle file/folder removal. All that is needed is an empty folder as source, your folder to clear as target and the /purge
switch will remove all files in target not present in source. File and folder retention is handled with /xf
(exclude files) and /xd
(exclude directories) switches
@echo off
setlocal enableextensions disabledelayedexpansion
set "target=%~1"
if not defined target set "target=%cd%"
set "excludedFiles=update.cmd foldername.zip"
set "excludedFolders=folderName"
2>nul (
for %%a in ("%temp%\%~nx0.%random%%random%%random%.tmp") do (
md "%%~fa"
robocopy "%%~fa" "%target%\." /l /s /e /nocopy /purge /xf %excludedFiles% /xd %excludedFolders%
rmdir /s /q "%%~fa"
)
)
The robocopy
command includes a /l
switch to only list the files/folders involved in the operation. If everything seems right, remove the /l
to perform file/folder removal.
Upvotes: 2
Reputation: 50640
You are misunderstanding how "Read Only" works for folders in Windows. It's not your fault. It's a misleading label. "Read Only" on a folder makes all files within the folder read only, but not the folder itself.
Note
Setting a folder to read-only makes all the files in the folder read-only. It does not affect the folder itself.
My apologies for quoting the Vista documentation, I wasn't able to find a similar page for folders for Windows 7. It is mentioned in the UI though:
We are going to set the system
attribute as well.
attrib +r update.bat
attrib +r FolderName.zip
attrib +r +s FolderName
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
attrib -r update.bat
attrib -r FolderName.zip
attrib -r -s FolderName
Example utilization:
Before running update, my directory contains the following:
<DIR> FolderName
FolderName.zip
New Bitmap Image.bmp
<DIR> New folder
New Microsoft Word Document.docx
New Text Document (2).txt
New Text Document (3).txt
New Text Document.txt
update.bat
After executing the update.bat
, the directory now looks like this:
<DIR> FolderName
FolderName.zip
update.bat
Upvotes: 3