0m3r
0m3r

Reputation: 12499

how to delete files and folders

How do I delete only files or folders that start with 2015 and 2014?

This is what I have so far, which it deletes all the files and folders under C:\Temp Folder

@TITLE = 
@ECHO ON

SET Folder="C:\Temp"

CD /D %folder%

FOR /F "Delims=" %%i IN ('DIR /B') DO (rmdir "%%i" /S/Q || DEL "%%i" /S/Q)

PAUSE

Upvotes: 0

Views: 140

Answers (2)

aschipfl
aschipfl

Reputation: 34899

You could use for loops to walk through the directory tree; for /R /D enumerates all subdirectories recursively, and for /R returns the files:

pushd "C:\Temp"
for /R /D %%I in ("2014*" "2015*") do (
    rmdir /Q "%%~fI"
)
for /R %%I in ("2014*" "2015*") do (
    del /Q "%%~fI"
)
popd

Or you let dir /B /S return all items, files and directories, and parse its output with a for /F loop:

pushd "C:\Temp"
for /F "eol=| delims=" %%I in ('
    dir /B /S "2014*" "2015*"
') do (
    2> nul rmdir /Q "%%~fI" || del /Q "%%~fI"
)
popd

The 2>nul redirection avoids error messages to be returned by rmdir, if the current item is a file.

Upvotes: 1

ZykoBot
ZykoBot

Reputation: 1

@TITLE = 
@ECHO ON
SET Folder="C:\Temp"
CD /D %folder%
FOR /F %%I IN ('DIR /B') DO (
  SET FOLDER=%%I
  SET FOLDER=%FOLDER:~0,4%
  IF %FOLDER% == 2015 GOTO Delete
  IF %FOLDER% == 2014 GOTO Delete
  GOTO End
  :Delete
  RMDIR "%%I" /S /Q || DEL "%%I" /S /Q
  :End
)
PAUSE

%FOLDER:~0,4% means that you take the first 4 characters of the variable 'FOLDER'

Upvotes: 0

Related Questions