English 中文(简体)
Batch File to Delete Folders
原标题:

I found some code to delete folders, in this case deleting all but n # of folders. I created 10 test folders, plus 1 that was already there. I want to delete all but 4. The code works, it leaves 4 of my test folders, except that it also leaves the other folder. Is there some attribute of the other folder that s getting checked in the batch file that s stopping it from getting deleted ? It was created through a job a couple of weeks ago.

Here s the code I stole (but don t really understand the details):

rem DOS - Delete Folders if # folders > n
@Echo Off
:: User Variables
:: Set this to the number of folders you want to keep
Set _NumtoKeep=4
:: Set this to the folder that contains the folders to check and delete
Set _Path=C:MyFolder_TempFolderTest
If Exist "%temp%	f}1{" Del "%temp%	f}1{"
PushD %_Path%
Set _s=%_NumtoKeep%
If %_NumtoKeep%==1 set _s=single
  For /F "tokens=* skip=%_NumtoKeep%" %%I In ( dir "%_Path%" /AD /B /O-D /TW ) Do (
    If Exist "%temp%	f}1{" (
      Echo %%I:%%~fI >>"%temp%	f}1{"
    ) Else (
      Echo.>"%temp%	f}1{"
      Echo Do you wish to delete the following folders?>>"%temp%	f}1{"
      Echo Date       Name>>"%temp%	f}1{"
      Echo %%I:%%~fI >>"%temp%	f}1{"
  ))
PopD
If Not Exist "%temp%	f}1{" Echo No Folders Found to delete & Goto _Done
Type "%temp%	f}1{" | More
Set _rdflag= /q
Goto _Removeold
Set _rdflag=
:_Removeold
For /F "tokens=1* skip=3 Delims=:" %%I In ( type "%temp%	f}1{" ) Do (
 If "%_rdflag%"=="" Echo Deleting
 rd /s%_rdflag% "%%J")
:_Done
If Exist "%temp%	f}1{" Del "%temp%	f}1{"
问题回答

The For /F line is the key. It takes the results of the part of the line in single quotes, and iterates over it.

So it takes a directory listing of the files in the target directory, excludes the first n lines based on the _NumtoKeep variable, and presents the results.

Then it asks a question with the Set _rdflag= /q line, confirming the action, before doing the work.

Use RD C:BLAH /S /Q command for Windows

There are two tools I can think of to check permission on the directory.

To remove readonly on the directories use

attrib -r /s <directory_name>

To view help on granting permissions on the directory

cacls /?




相关问题
complex batch replacement linux

I m trying to do some batch replacement for/with a fairly complex pattern So far I find the pattern as: find ( -name *.php -o -name *.html ) -exec grep -i -n hello {} + The string I want ...

How to split a string by spaces in a Windows batch file?

Suppose I have a string "AAA BBB CCC DDD EEE FFF". How can I split the string and retrieve the nth substring, in a batch file? The equivalent in C# would be "AAA BBB CCC DDD EEE FFF".Split()[n]

How to check which Operating System?

How can I check OS version in a batch file or through a vbs in an Windows 2k/2k3 environment ? You know ... Something like ... : "If winver Win2k then ... or if winver Win2k3 then ....

热门标签