Solved

Delete folder if empty

Posted on 2010-11-18
27
567 Views
Last Modified: 2012-05-10
I need to create a batch file that does 2 things:

1) Checks if folder C:\Test is empty and if it is, delete it

2) Delete all the files from folder C:\Research except 2 files test1.ico and test2.ico
0
Comment
Question by:YZlat
  • 13
  • 12
  • +1
27 Comments
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34167603
For (1) you can just try to delete the folder, and if it is not empty, it will fail.  So the code:

del c:\test >nul 2>&1

Open in new window

will suppress any errors, and will only delete the folder if it is already empty.

~bp
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34167626
Sorry, that should have been:

rd c:\test >nul 2>&1

Open in new window

~bp
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34167645
for (2), this should work:

for %%A in ("c:\research"\*"") do (
  if "%%~nxA" NEQ "test1.ico" (
    if "%%~nxA" NEQ "test2.ico" (
      del "%%A"
    )
  )
)

Open in new window

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34167724
neither first nor second suggestions worked. i am gonna try the third one now
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34167734
Post 34167626 should delete the c:\test folder if it exists, and has no folders or files within it.

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34167951
it didn't delete folder c:\test even though it was empty
0
 
LVL 35

Author Comment

by:YZlat
ID: 34167971
the second part worked for files but not for subfolders inside C:\Research
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34167984
please do the following command from a prompt and let's see what it says.  Naturally if you don't have delete permissions against the folder it will fail as well.

rd c:\test

~bp
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34168024
==> the second part worked for files but not for subfolders inside C:\Research

Yup, that's because you asked for:

"Delete all the files from folder C:\Research except 2 files test1.ico and test2.ico"

Here's how to get rid of the subfolders too:

@echo off

REM Remove all subfolders
for /D %%A in ("c:\research\*") do (
  rd /S /Q "%%A"
)

REM Remove all files except 2 special files to be kept
for %%A in ("c:\research\*") do (
  if "%%~nxA" NEQ "test1.ico" (
    if "%%~nxA" NEQ "test2.ico" (
      del "%%A"
    )
  )
)

Open in new window

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34168178
rd C:\Test does not work

only

rd C:\Test  /S /Q
0
 
LVL 35

Author Comment

by:YZlat
ID: 34168302
@echo off

REM Remove all subfolders
for /D %%A in ("c:\research\*") do (
  rd /S /Q "%%A"
)

REM Remove all files except 2 special files to be kept
for %%A in ("c:\research\*") do (
  if "%%~nxA" NEQ "test1.ico" (
    if "%%~nxA" NEQ "test2.ico" (
      del "%%A"
    )
  )
)

deleted everything
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34168397
Perhaps the ICO files fto be kept were not all in lower case?  To cover that case make this adjustment:

 if /I "%%~nxA" NEQ "test1.ico" (
    if /I "%%~nxA" NEQ "test2.ico" (

~bp
0
 
LVL 11

Expert Comment

by:louisreeves
ID: 34168407
I took a look at this and though this might be nice to have. Upon further review, IT looks like this is highly undesirable on todays machines. you should never run a batch file to delete mass folders on your system. At least make it a two step process:

DIR /AD/B/S | SORT /R > LOOKATWHATYOU MIGHTBEDELETING.BAT

You will notice may GUID and other blank folders that are of questionable purpose. Do you really want to delete all those?

The next step is to just use the find in replace in word and find ^p and replace with "^pRD "

--------------

As far as leaving a file in the folder. that is not as Batch friendly. THis is more flexible in a .vbs file

strFolder = "c:\yourfolder"  
 
Set Exceptions = CreateObject("Scripting.Dictionary")  
 
Set FSO = CreateObject("Scripting.FileSystemObject")  
 
Exceptions.CompareMode = vbTextCompare  
 
Exceptions.Add "test1.ico", ""  
 
Exceptions.Add "test2.ico", ""  
 
 
Set objFolder = FSO.GetFolder(strFolder)  
 
For Each File in objFolder.Files  
 
If LCase(FSO.GetExtensionName(File)) = "ico" Then  
 
If Not Exceptions.Exists(File.Name) Then FSO.DeleteFile File  
 
End If  
 
Next


Those are 2 possible wayt to go. I hope this helps
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 35

Author Comment

by:YZlat
ID: 34173691
billprew, the file names were in lower-case

louisreeves, I am using batch file, so your code will not work for me
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34173793
==> billprew, the file names were in lower-case

Hmm, not sure how the second group of logic could be deleting the "special" files, try adding an echo in and see if it lists those files.

REM Remove all files except 2 special files to be kept
for %%A in ("c:\research\*") do (
  echo Processing: [%%A]
  if "%%~nxA" NEQ "test1.ico" (
    if "%%~nxA" NEQ "test2.ico" (
      echo Deleting: [%%A]
      del "%%A"
    )
  )
)

Open in new window

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34174089
billprew, please help

when I use

rd "C:\Test\"

the folder does not get deleted even if it is empty and I get Access denie error

and when I use

rd "C:\Test\"  /S /Q

everything gets deleted even if there are files in the directory
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34175762
So if you do:

MD C:\FOO
RD C:\FOO


does the RD fail?

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34176710
I think I found the issue - for some reason it looks at my folder as if it has 1 file in there while in fact it's empty.  I believe it's hidden ini for folder customization since it's a customized folder.
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34181208
If you know the name the file that needs to be deleted, then you could try the following, to remove the  files from the folder first.

DEL /F /Q /A:RHS filename.ext


~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34197098
I am not 100% sure about the name
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34197239
Try doing DIR /A:H or DIR /A:S to try and see what file might be causing a problem.

~bp
0
 
LVL 14

Expert Comment

by:canali
ID: 34222462

Another way for the same problem... with logging, attrib+permission+ownership for remove everything ;)

Bye Gastone Canali
@echo off
::
:: Bye Gastone Canali
::
set filename=%~n0
set logfile="c:\temp\_%filename%.txt"
set null= 2^>^&1
set log=^>^>%logfile% 2^>^&1
:: *** no log remove the :: in the next line
:: set log=

:: ***  
set Dir2del=c:\temp\test
:: *** takeown, change permission/attrib
takeown /F      "%Dir2del%\*"   /R /a  /D Y               %log%
echo y|cacls    "%Dir2del%\*.*" /T /E /C /G %username%:F  %log%
attrib -r -h -s "%Dir2del%\*.*"                           %log%
:: *** remove test if empty
rd  /Q "%Dir2del%"                                        %log%

:: *********************************************************
set RES=c:\temp\research
:: *** change DIR
(pushd "%RES%") || goto :_ERR
:: *** takeown, change permission/attrib
takeown /F * /R /a  /D Y                      %log%
echo y|cacls *.* /T /E /C /G %username%:F     %log%
attrib -r -h -s *.*                           %log%

:: *** Remove all subfolders
for /f  "delims=:" %%D in ('dir /b /a:d') do (
    rmdir /S /Q "%%D"
) %log%
:: *** Remove all files except 2 special files to be kept
for /f  "delims=:" %%F in ('dir /b /a:-d^|findstr /i /v "test1.ico test2.ico"') do (
    del /F /Q "%%F"
) %log%
:_ERR

:_END

Open in new window

0
 
LVL 35

Author Comment

by:YZlat
ID: 34319063
billprew, is there a way to detect hidden files in that folder?
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 34323656
==> billprew, is there a way to detect hidden files in that folder?

Yes, that's what the DIR /A:H C:\Temp\*.* will do.

In addition, to delete just hidden files, you can do DEL /A:H /Q C:\Temp\*.*

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34335810
billprew, how can I detect and delete hidden files with VBScript?
0
 
LVL 51

Accepted Solution

by:
Bill Prew earned 250 total points
ID: 34337452
Sorry, thought we were working BAT, thanks for the heads up on the VBS question.  You just use the Attributes property of a File object once you have it, as documented in:

http://msdn.microsoft.com/en-us/library/5tx15443%28v=VS.85%29.aspx

Take a look and let me know if that makes sense, or if you have a piece of code you want me to peek at.  Are you pursuing a VBS approach at this point?

~bp
0
 
LVL 35

Author Comment

by:YZlat
ID: 34377422
BAT didn't work out for me as well, so I started using VBS and just calling VBS files from BAT.

I really appreciate all your help
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Over the years I've spent many an hour playing on hardened, DMZ'd servers, with only a sub-set of the usual GNU toy's to keep me company; frequently I've needed to save and send log or data extracts from these server back to my PC, or to others, and…
Introduction: Recently, I got a requirement to zip all files individually with batch file script in Windows OS. I don't know much about scripting, but I searched Google and found a lot of examples and websites to complete my task. Finally, I was ab…
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now