i've engaged with work in batch script.these things i need to do
1.i want to find the folder say like "name" in particular directory
ex:
c:\test\name
c:\test\b\name
c:\test\n\c\name
2.in the name folder, need to delete all sub folders and files and all which is more than 90 days.
i have changed my question now please give me an idea...
#ECHO OFF
SETLOCAL
SET "targetdir=U:\destdir"
ECHO(DEL "%targetdir%\*?*"
FOR /f "delims=" %%a IN (
'dir /b /ad "%targetdir%\*" '
) DO (
ECHO(RD /S /Q "%%~a"
)
GOTO :EOF
You would need to change the setting of targetdir to suit your circumstances. It could of course be replaced by a literal if you wish.
The required RD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(RD to RD to actually delete the directories.
The required DEL commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(DEL to DEL to actually delete the files.
the del and for commands could be cascaded with a & if required. The for is spread across a nuber of lines for clarity.
You're missing an asterisk * so that the folder set expands to all subdirectories of the _delete folder. Also, the /D /R construct seems unnecessary on second thought, because RD /S does already take care of deleting directories recursively.
FOR /D %%A IN ( folder_you_want_to_clean\* ) DO IF EXIST "%%A" RD /S /Q "%%A"
But it won't delete the files in the folder_you_want_to_clean folder itself, though. Do that with the DEL command - the /Q option suppresses the confirmation prompt, just like with the RD command:
DEL /Q folder_you_want_to_clean\*
Concrete example: Suppose the folder you want to clean is C:\data\oldstuff. Then just do:
FOR /D %%A IN ( C:\data\oldstuff\* ) DO IF EXIST "%%A" RD /S /Q "%%A"
All directories contained in C:\data\oldstuff will be gone (and of course, any files in those directories). But any files in C:\data\oldstuff itself will still be there! So to delete those as well, do:
DEL /Q C:\data\oldstuff\*
Related
I want to delete a specific directory on Windows. I use the code below. It works fine. I want to put the .bat file I made for this process in that directory. Naturally, the .bat file is also deleted. I want the .bat file to be excluded from this deletion. What should I do with the code?
Echo batch file delete folder
#RD /S /Q "D:\testfolder"
All you have to do is to lock your batch file, by opening a dummy read handle to it.
echo The batch file wont be deleted because it is locked by a dummy input redirection.
rd /s /q "D:\testfolder" 9<"%~f0"
Naturally, an error message will be shown by the rd command, because there is at-least one file in the target directory (your own batch file) which can not be deleted. You can hide that message by redirecting the standard error stream to the nul device:
rd /s /q "D:\testfolder" 9<"%~f0" 2>nul
There are several ways to achieve your task.
The method, (especially as you generally remove directories with one command, and delete files with another), is to identify the files and subdirectories separately. First identify the subdirectories and remove those, using the RD command, then delete all files except for the batch file itself, %0:
You could do that in one line using the ForFiles utility:
#%SystemRoot%\System32\forfiles.exe /P "%~dp0." /C "%SystemRoot%\System32\cmd.exe /C If #IsDir==TRUE (RD /S /Q #File) Else If /I Not #file == \"%~nx0\" Del /A /F #File"
Or you could use a For loop, with the Dir command:
#For /F Delims^=^ EOL^= %%G In ('Dir /B /A "%~dp0"') Do #If "%%~aG" GEq "d" (RD /S /Q "%%G") Else If /I Not "%%G" == "%~nx0" Del /A /F "%%G"
Please note that you can only remove/delete items for which you have the required permissions.
I would walk through the items in the folder whose contents you want to delete, remove one after another, except its name equals the name of the batch file:
rem // Change into target directory:
pushd "%~dp0." && (
rem /* Loop through immediate children of the target directory, regarding even
rem hidden and system items; to ignore such (replace `/A` by `/A:-H-S`): */
for /F "delims= eol=|" %%I in ('dir /B /A "*"') do (
rem // Check name of current item against name of this batch script:
if /I not "%%~nxI"=="%~nx0" (
rem /* Assume the current item is a sub-directory first (remove by `rd`);
rem when removal fails, try to delete it as a file (done by `del`): */
rd /S /Q "%%I" 2> nul || del /A /F "%%I"
)
)
rem // Return from target directory:
popd
)
I have the following file and folder structure (using real names):
Carabidae/Pterostichinae/FolderNameXXX/dor/StackXXX/files.tif
My problem is that I need to get one specific file, PM*.*, from the StackXXX folders into their respective /dor parent folders. The StackXXX folder can then be deleted.
There are hundreds of FolderName. Ideally I would like a batch file I can run from the Carabidae folder.
This needs to be a batch file because there will be new FolderNames added constantly.
After a lot of searching, I found a semi-working solution from this StackOverflow answer:
for /f "delims==" %%i in ('dir /a:d /b') do for /f "delims==" %%f in ('dir %%i /a:d /b') do (move "%%i\%%f\PM*.*" "%%i"&&rd "%%i\%%f" /s /q)
It moves the file and deletes the folder, just as I want. But the problem is that it only works when run from a FolderName folder, which defeats the time-saving purpose of the script. I don't know how to modify it to recurse into subfolders so I can run it from the top folder.
Thank you very much for any help!
#ECHO OFF
SETLOCAL
SET "sourcedir=u:\Carabidae"
FOR /f "tokens=1*delims=" %%a IN (
'dir /b /s /a-d "%sourcedir%\pm*.*" '
) DO IF EXIST "%%a" (
FOR %%p IN ("%%~dpa..\.") DO IF /i "%%~nxp"=="dor" (
ECHO %%a|FINDSTR /i "\\dor\\Stack" >NUL
IF NOT ERRORLEVEL 1 (
ECHO MOVE /y "%%~dpa\pm*.*" "%%~dpa..\"
ECHO RD /s /q "%%~dpa"
)
)
)
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
Find all of the pm*.* files, filenames to %%a
Ensure the parent directory is dor and ensure that \dor\stack\ is in the path. If so, move the file(s) and remove the directory.
The if exist gate ensure no hiccoughs if a target directory contains more than one pm*.* file.
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
The required RD commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(RD to RD to actually delete the directories.
Add >nul at the end of the move command to suppress the move-report if required.
As usual, I'd suggest you test against a representative subtree first.
Here is a possible solution, given that only the XXX parts in your path sample are variable:
rem // Enumerate `FolderName*` directories:
for /D %%R in ("Carabidae\Pterostichinae\FolderName*") do (
rem // Enumerate `Stack*` sub-directories within `dor` sub-directories:
for /F "delims= eol=|" %%D in ('dir /B /A:D "%%~R\dor\Stack*"') do (
rem // Check for `PM*.*` files in `Stack*` sub-directories:
(
rem // Enumerate `PM*.*` files:
for /F "delims= eol=|" %%F in ('dir /B /A:-D "%%~R\dor\%%D\PM*.*"') do (
rem /* Move `PM*.*` file one directory level up, overwriting
rem an already existing file, if applicable: */
ECHO move /Y "%%~R\dor\%%D\%%F" "%%~R\dor\%%F"
)
) && (
rem /* Remove `Stack*` sub-directory after file movement;
rem this is skipped if no `PM*.*` files have been found in the `Stack*`
rem sub-directory, so when the `for /F %%F` loop did never iterate: */
ECHO rd /S /Q "%%~R\dor\%%D"
)
)
)
After having successfully tested whether or not the correct items are returned, remove the upper-case ECHO commands to actually move PM*.* files and remove Stack* directories!
I'm trying to write a simple batch file that will clean up disk space. I have to delete the entire contents (folders and files) of 4 different directories, but only if they exist. I've been testing trying to delete one, but I know nothing about writing batch files. After all the research I've done, I came up with a couple lines of code that doesn't work.
#echo off
IF EXIST "C:\Windows\TestFolder\TestSubFolder\*.*"
DEL /s /q "C:\Windows\TestFolder\TestSubFolder\*.*"
for /d %%p in ("C:\Windows\TestFolder\TestSubFolder\*.*") do rmdir "%%p" /s /q
exit
In this scenario, I need to be able to delete the contents of TestSubFolder, if TestSubFolder exists. Whether it exists or not, after that action is complete, I need the code to do the same thing to a TestSubFolder2.
Thanks
The main problem in your code is the improper usage of the if command. If there is only one command to execute if the condition is true, it can be written in the same line, but to write the command in the next line you need to use parenthesis. It should be something like
IF EXIST "C:\Windows\TestFolder\TestSubFolder\*.*" (
DEL /s /q "C:\Windows\TestFolder\TestSubFolder\*.*"
for /d %%p in ("C:\Windows\TestFolder\TestSubFolder\*.*") do rmdir "%%p" /s /q
)
But this can be simplified as
2>nul pushd "C:\Windows\TestFolder\TestSubFolder" && (
rmdir . /s /q
popd
)
That is, we try to change to the indicated folder (pushd) and if there was not any problem (conditional execution operator && means execute next command if the previous one did not fail) them remove all the contents of the folder (rmdir) and return to the previous active directory (popd). The 2>nul is just hidding any error message (ex. the folder does not exist, locked files that can not be removed, ...)
Now, if the process has to be repeated for more than one folder, we can use the for command to iterate over the list of the folders
for %%a in ( "folder1" "folder2" ) do ....
Placing the previous code into this for loop we have
#echo off
setlocal enableextensions disabledelayedexpansion
2>nul (
for %%a in (
"C:\Windows\TestFolder\TestSubFolder"
"C:\Windows\TestFolder\TestSubFolder2"
) do pushd "%%~fa" && (
rmdir . /s /q
popd
)
)
The error hidding has been moved to cover all the for execution, and now, for each of the folders (referenced by the for replaceable parameter %%a), we try to change to the folder using the full path (%%~fa) and if we can change to it, then remove all the folder contents before returning to the original active directory.
CD "C:\Windows\TestFolder\TestSubFolder"
RD /s /q "C:\Windows\TestFolder\TestSubFolder"
Works for me.
or from anywhere
RD /s /q "C:\Windows\TestFolder\TestSubFolder"
MD "C:\Windows\TestFolder\TestSubFolder"
I have a data set consisting of files organised according to the following hierarchical folder/subfolder structure:
I would like to remove all nuisance subfolders (move its contents outside of it at the same hierarchical level + delete the nuisance folder), thus ending up with the files organised like this:
How can I achieve this, using a batch file, run from a command prompt inside Windows 7? I've tried a number of for statements with %F and %%F, but none worked. Grateful for any tips.
I believe the following will accomplish your goal if and only if all child folder and file names are unique. If there are duplicates, then all hell will break loose.
I have not tested, so backup and/or try the code on disposable data first.
You will have to modify the first PUSHD command to point to the root where all your "person n" folders reside.
#echo off
pushd "yourRootWherePersonFoldersReside"
for /d %%U in (*) do (
pushd "%%U"
for /f "eol=: delims=" %%A in ('dir /b /ad 2^>nul') do (
for /d %%B in ("%%A\*") do (
for /d %%C in ("%%B\*") do (
md "%%~nxC"
for /d %%D in ("%%C\*") do move "%%D\*" "%%~nxC" >nul 2>nul
)
)
rd /s /q "%%A"
)
popd
)
popd
The second FOR loop must be FOR /F instead of FOR /D because FOR /D has the potential to iterate folders that have been added after the loop has begun. FOR /F will cache the entire result of the DIR command before iteration begins, so the newly created folders are guaranteed not to interfere.
I want to have a batch file that will delete all the folders and files in my cache folder for my wireless toolkit.
Currently I have the following:
cd "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS"
del *.db
This will delete all .db files in my RMS directory, however I want to delete every single thing from this directory. How can I do this?
Use:
Create a batch file
Copy the below text into the batch file
set folder="C:\test"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
It will delete all files and folders.
del *.* instead of del *.db. That will remove everything.
IF EXIST "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" (
rmdir "C:\Users\tbrollo\j2mewtk\2.5.2\appdb\RMS" /s /q
)
This will delete everything from the folder (and the folder itself).
I just put this together from what morty346 posted:
set folder="C:\test"
IF EXIST "%folder%" (
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)
It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.
del *.* will only delete files, but not subdirectories. To nuke the contents of a directory, you can use this script:
#echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START
:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE
:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd
:DONE
endlocal
The pushd changes into the directory of which you want to delete the children. Then when rd asks to delete the current directory and all sub directories, the deletion of the sub directories succeed, but the deletion of the current directory fails - because we are in it. This produces an error which 2> NUL swallows. (2 being the error stream).
You can do this using del and the /S flag (to tell it to recurse all files from all subdirectories):
del /S C:\Path\to\directory\*
The RD command can also be used. Recursively delete quietly without a prompt:
#RD /S /Q %VAR_PATH%
Rmdir (rd)
set "DIR_TO_DELETE=your_path_to_the_folder"
IF EXIST %DIR_TO_DELETE% (
FOR /D %%p IN ("%DIR_TO_DELETE%\*.*") DO rmdir "%%p" /S /Q
del %DIR_TO_DELETE%\*.* /F /Q
)
Use
set dir="Your Folder Path Here"
rmdir /s %dir%
mkdir %dir%
This version deletes without asking:
set dir="Your Folder Here"
rmdir /s /q %dir%
mkdir %dir%
Example:
set dir="C:\foo1\foo\foo\foo3"
rmdir /s /q %dir%
mkdir %dir%
This will clear C:\foo1\foo\foo\foo3.
(I would like to mention Abdullah Sabouin's answer. There was a mix up about me copying him. I did not notice his post. I would like to thank you melpomene for pointing out errors!)
Try the following; it works for me.
I have an application which dumps data in my "C:\tmp" folder, and the following works the best for me. It doesn't even ask Yes or No to delete the data. I have made a schedule for it to run after every 5 minutes
cd "C:\tmp"
del *.* /Q
Better yet, let's say I want to remove everything under the C:\windows\temp folder.
#echo off
rd C:\windows\temp /s /q
You could use robocopy to mirror an empty folder to the folder you are clearing.
robocopy "C:\temp\empty" "C:\temp\target" /E /MIR
It also works if you can't remove or recreate the actual folder.
It does require an existing empty directory.
I would like to suggest using simple tool like cleardir. So, in batch file you can write:
cleardir path/to/dir
And you'll get empty directory dir. A bit slow, but still resolves the "problem".
I'm an author of the tool =)
The easiest way is:
Create *.txt file
Write:
rmdir /q /s . dir
Save file as *.bat in folder which you want to clear (you can call the file NUKE.bat)
Turn it on
WARNING!
THIS DELETES EVERYTHING IN THE FOLDER WHERE IT IS WITHOUT ASKING FOR CONFIRMATION!!!
SO CHOOSE WISELY PLACE FOR SAVING IT.
Easy simple answer :
C:
del /S /Q C:\folderName\otherFolderName\*
C: Important in case you have to switch from D: to C: or C: to D: (or anything else)
/S Recursive, all subfolders are deleted along
/Q If you don't activate quiet mode, prompt will ask you to type y for every subfolders... you don't want that
Be carful, it's drastic.
You cannot delete everything with either rmdir or del alone:
rmdir /s /q does not accept wildcard params. So rmdir /s /q * will error.
del /s /f /q will delete all files, but empty subdirectories will remain.
My preferred solution (as I have used in many other batch files) is:
rmdir /s /q . 2>NUL
Just a modified version of GregM's answer:
set folder="C:\test"
cd /D %folder%
if NOT %errorlevel% == 0 (exit /b 1)
echo Entire content of %cd% will be deleted. Press Ctrl-C to abort
pause
REM First the directories /ad option of dir
for /F "delims=" %%i in ('dir /b /ad') do (echo rmdir "%%i" /s/q)
REM Now the files /a-d option of dir
for /F "delims=" %%i in ('dir /b /a-d') do (echo del "%%i" /q)
REM To deactivate simulation mode remove the word 'echo' before 'rmdir' and 'del'.
#echo off
#color 0A
echo Deleting logs
rmdir /S/Q c:\log\
ping 1.1.1.1 -n 5 -w 1000 > nul
echo Adding log folder back
md c:\log\
You was on the right track. Just add code to add the folder which is deleted back again.