How to delete specific hidden sub folders recursively with batch - batch-file

A bad program left several ".data" hidden folders in every sub directory.
I have tried this so far, and it doesn't work...
RD /ah /s /q "D:\This Folder\.data"
I have many folders and sub-folders, each one has a ".data" hidden folder there that I would like to remove. If it helps, I would like to delete all the hidden folders because they are all ".data".

#echo off
setlocal enableextensions disabledelayedexpansion
for /f "delims= eol=" %%a in ('
dir /adh /s /b 2^>nul
') do if /i "%%~nxa"==".data" echo rd /s /q "%%~fa"
This executes a dir command to retrieve a recursive (/s) list of hidden directories (/ahd) in bare format (/b). This list is processed by a for /f command that will check for each match if it is a .data folder. If it matches the condition, the folder and its contents are removed.
note the rd commands are only echoed to console. If the output is correct, remove the echo command.

#ECHO OFF
for /f "tokens=*" %%F in ('dir /s /b /o:n /adh') do (
if "%%~nxF"==".data" rd /s /q "%%F"
)
dir /s /b /o:n /adh gives you all folders and subfolders skipping files. for /f iterates over all these folders. %%~nxF extracts the last folder name from the whole path so we can check whether it is .data. If this is the case rd /s /q %%F deletes the folder.

Read what you get when you type for /? then:
Use the /d
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
and the /r switches together
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.
To scan folders recursivly
for /d /r . %%a in (data*) do rd /s /q "%%a"

Related

Batchfile to delete all folders but the latest AND a special folder

hope you can help me. I am looking for a way to use batchscript to delete all folders in a subfolder except
the very newest folder AND
a special folder named "BACKUP".
So the backup folder can be older, but it needs to be kept.
All other folders except the one with the newest date should be deleted.
There will be files in all of those folders, but there are no hidden files or subfolders, so this needs not to be considered in this case.
I found a lot of solutions here to either spare the backup folder or delete everything except the newest, but I cannot seem to find a solution that can do both.
for /d %%i in ("C:\Parent\*") do if /i not "%%~nxi"=="BACKUP" del /s /q "%%i"
I.e. like this, but it will not keep the newest folder.
All the other folders except the backup folder have names like "20220215" "20210405".
Thank you for any help you can give.
KR
Susanne
Build a list of directories by dir sorted by age from newest to oldest, filter out unwanted ones by findstr, then use for /F to iterate through the list but skip the very first item:
rem // Change into root directory:
pushd "C:\Parent" && (
rem /* Loop through matching directories sorted by last modification date (due to `/T:W`)
rem in descending order and skip the very first (that is the lastly modified) item: */
for /F "skip=1 delims= eol=|" %%I in ('
dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /V /I /X "BACKUP"
') do rd /S /Q "%%I"
rem // Return from root directory:
popd
)
Since del only deletes files, rd is used instead to delete (sub-)directories too rather than leaving behind empty (sub-)directory trees.
The line dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /V /I /X "BACKUP" could be replaced by the following in order to do stricter filtering:
dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /I /X "[12][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]"
set "skipme=Y"
for /f "delims=" %%b in ('dir /b /ad /od "c:\parent\*"') do if /i "%%b" neq "backup" if defined skipme (set "skipme=") else (ECHO rd /s /q "c:\parent\%%b")
Should remove all the required directories. Well, report the directorynames that would be delete if the echo keyword was deleted.
skipme is initialised to a value. for each directory found, with the exception of backup, check whether skipme has a value; set skipme to empty if it's set (which will only be for the first directory found that isn't backup from a date-ordered dir list), otherwise remove the directory.

How to exclude folders from being deleted using a for loop in a Batch script?

I am trying to delete everything in a user defined location with exception on one pre-defined folder using a for loop. How do I go about adding a exception in order to not delete a folder.
I am trying to learn how to code, but I admit I am doing baby steps. I got some excellent tips for the first input part of this script, but I lack the knowledge to move forward. I have searched and found similar code, but none seems to work. This script is intended for flight simulation and hopefully ease the workload of installing a particular item.
This is just the part of the code due to stackoverflow guidelines, it deletes everything including the folder I want to exclude.
...
Rem This code is intended to delete all except one pre-defined folder
Echo Deleting all the files except testmappe3
del /s /q "%CD%"
for /d %%p in ("%CD%") do rmdir "%%p" except "%%testmappe3" /s /q
dir
Pause
...
I expected the output to delete all folders except testfolder3
for /d %%A in ("%CD%\*") do (
set "except="
if /i "%%~nxA" == "testmappe3" set "except=1"
if not defined except rmdir /s /q "%%~A"
)
This code will iterate the folders in the current directory.
If the name+extension of the folder is testmappe3,
then except will be set as 1 i.e. defined with a value.
If except is not defined, rmdir will remove the folder.
You can add more if lines for checking folders to except.
The modifiers will recognize a folder such as named
testmappe3.test1 as name testmappe3 and
extension of .test1.
View for /? and call /? about modifiers.
View for /?, set /?, if /? and rmdir /? for
help with those commands.
First of all, I would be a very careful deleting everything using %cd% especially if the script can accidently be run as Administrator, where %cd% would then be c:\windows\system32.
Instead, use %~dp0 as path to ensure that you are in the correct directory. This all assumes you did not cd somewhere else earlier in the script.
Then to the actual issue, I would include findstr to exclude your directory `testmappe3 as well as your script itself.
#echo off
cd /d "%~dp0"
for /f %%p in ('dir /b ^| findstr /vi /r /c:^testmappe3$') do (
rmdir "%%p" /s /q >nul 2>&1
if not "%%p"=="%~nx0" del /s /q "%%p" >nul 2>&1
)
If you want to stick to your original delete method, then it would be as below, but if your script is in the same dir, then it will also be deleted:
#echo off
cd /d "%~dp0"
del /s /q *
for /f %%p in ('dir /b ^| findstr /vi /r /c:^testmappe3$') do (
rmdir "%%p" /s /q >nul 2>&1
)
If your folder to exclude contains spaces, double quotes are required.. i.e
dir /b ^| findstr /vi /r /c:^"test mappe3"$

xcopy batch issue

I want to copy a set of subfolders where name contains items on a list. The list has a set of codes (e.g. ABC1, ABC2) but the folders are named ABC1_revised_2018, etc. My batch file I put together is below. What I am getting a '"Usebackq tokens=^" was unexpected' error.
#ECHO ON
SET FileList=C:\filelist.txt
SET Source=C:\Files
SET Destination=C:\Files-Parsed
FOR /D "USEBACKQ TOKENS=^" %%D IN ("%FileList%") DO XCOPY /E /F /D "%Source%\%%~D" "%Destination%\"
GOTO :EOF
I am attempting to use ^ to denote match beginning of string but that clearly isn't working. Any ideas? I have tried with a batch file and also line by line in cmd.
append
Folder
-ABC1-text-date (this is a subfolder)
-ABC2-text-date
filelist.txt only has values like ABC1, ABC2, etc. not exact matches does this help?
Well, if you want to recurse through directories and copy sub directories as per partial matches inside the file:
#echo off
set "FileList=C:\filelist.txt"
set "Source=C:\Files"
set "Destination=C:\Files-Parsed"
for /f "delims=" %%a in (%filelist%) do (
pushd %source%
for /f "delims=" %%i in ('dir /s /b /ad "%%a*"') do xcopy /E /F /D "%%~fi" "%Destination%"
popd
)
after getting the entry in the file, for /d will do a directory listing of the directory* in the source directory and physically copy the dir as C:\source\*\ABC2018 etc.

How to delete directories containing certain string using batch file in Windows?

From
How to delete files containing certain string using batch file in Windows?
I learned how to mass delete files which contain certain strings. What I did is
del *(2)* /f /s
but this did not delete directories. It only delete files.
How can I also mass-delete directories which contain certain strings?
There's no standard Windows command to delete files and directories on the same level. DEL is used for files, RMDIR / RD is used for directories (however it can delete files within directories).
RMDIR / RD does not work with wildcards, so you need to use a FOR loop. As it is, the below code will print out the commandos to delete the directories in your question. Remove the ECHO when you're confident the deletion will do what you want.
#ECHO OFF
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S "*(2)*"') DO (
ECHO RMDIR /S /Q "%%G"
)
You can also reduce this to a one-liner...
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S "*(2)*"') DO ECHO RMDIR /S /Q "%%G"
...and if you want to execute it directly in the shell (as opposed to from a .bat file), do:
FOR /F "tokens=*" %G IN ('DIR /B /AD /S "*(2)*"') DO ECHO RMDIR /S /Q "%G"
Flags explanation:
FOR
/F: iterate over a fileset
DIR
/B: bare format (needed so it works with FOR)
/AD: filter for directories
/S: work recursive
RMDIR
/S: work recursive
/Q: quiet mode

Delete everything from Subfolders through Batch file

I have directories like:
c:\Project\Current\stage1\somefiles and some folders
c:\Project\Current\stage2\somefiles and some folders
c:\Project\Current\stage3\somefiles and some folders
c:\Project\Current\stage4\somefiles and some folders
c:\Project\Current\stage5\somefiles and some folders
.
.
.
c:\Project\Current\stage500\somefiles and some folders
I want to create a batch file so that everything inside stage1, stage2,..., stage500 will get deleted but not any of other folders so that I can still see the above directories but empty.
Can someone please help?
Try this:
#echo off
CD c:\Project\Current /d
for /f "tokens=*" %%f in ('dir /a-d /s /b') do (
del "%%f" /q /f
)
There are three important parts:
for /f "tokens=*" %%f means we are iterating over all lines that are generated by the following command and temporarily save each line in the variable %%f for each iteration.
dir /a-d /s /b is the core of the code. This will list all files inside c:\Project\Current\ including all subfolders. /a-d means that directories will be ignored as we don't want them to be erased. /s means we are searching any subfolder. /b sets the output format to simple mode so that each line of the output will contain nothing but the full path to a file.
del "%%f" /q /f simply deletes the file which is stored in %%f. /q means "don't ask me if I'm sure, just erase it" and /f means that any file - even if it is marked as system file or as invisible or protected - will be deleted. Don't miss the quotation marks around %%f as otherwise paths containing spaces will cause trouble.
I found the answer and is very simple
for /d %%X in (c:\Project\Current*) Do (
for /D %%I in ("%%X\*") do rmdir /s/q "%%I"
del /F /q "%%X\*")
Thanks for everyone's help..

Resources