Solved

Delete folder if empty

Posted on 2010-11-18
27
575 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 54

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 54

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 54

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
Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

 
LVL 35

Author Comment

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

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 54

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 54

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 54

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
 
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 54

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 54

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 54

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 54

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 54

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 54

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of my most closely kept secrets is revealed in this discussion How to output text on the same line This question was recently posted in EE by Simon336697 (http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Batch/Q_2459…
Utilizing an array to gracefully append to a list of EmailAddresses
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 a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

730 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