Batch deleting folders from file.txt - batch-file

I have a temp folder where files get loaded into and then systematically purged out. Job to clear out files failed and now I have a number of directories/files that need to be manually deleted. I have deletedirs.txt that contains the names of all the folders I need deleted. I have generated the following to delete the files and folders however the path is not always the same:
FOR /F %%i IN (C:\dirlist.txt) DO echo y| del "C:\Temp Files\*" & rmdir /s /q "C:\Temp Files\" %%i
The issue is as the temp files get loaded in they form their own subfolder(s) so I have the following structure:
C:\Temp Files\101\folder1
C:\Temp Files\101\folder2
C:\Temp Files\103\folder4
C:\Temp Files\455\folder3
deletedirs.txt contains the folder names (folder1, folder2, etc.)
My script is failing because its searching for "C:\Temp Files\folder1"
How can I get the script to find 'folder1' and remove it regardless of subfolder number (101, 103, etc.)?

#ECHO OFF
SETLOCAL
FOR /d %%a IN ("c:\temp\*") DO (
FOR /f "delims=" %%s IN (q48890405.txt) DO (
IF EXIST "%%a\%%s\." ECHO RD /S /Q "%%a\%%s"
)
)
GOTO :EOF
You would need to change the directoryname to suit your circumstances.
I used a file named q48890405.txt containing some dummy data for my testing.
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.
This should assign the subdirectory names to %%a in turn, then for each subdirectory found, read the names from the file into %%s. Then see whether a directory named %%a\%%s exists, and delete it if it does exist.
Note that your del "C:\Temp Files\*" will simply delete all of the files in "C:\Temp Files" over and over again. It really only needs to be done once (if that's what you had intended to do).
Removing the directory disposes of all of the files it contained, provided none are protected in some way (read-only or by UAC).

Related

how to copy only modified files using LogFile.txt?

when it comes to creating a batch-file I would sadly call myself a newbie and therefore it's kind of difficult for me to achieve what I want on my own:
so here is how my codes look:
#ECHO OFF
for /r "C:\source" %%f in (*) do copy /y "%%f" C:\ReadyToExport
del C:\ReadyToExport\*.pdf*
for /f "delims=" %%i in ('xcopy "C:\ReadyToExport" C:\import /EXCLUDE:LogFile.log /S /E /D') do (
echo %%i >> C:\LogFile.log)
PAUSE
and here is what the code exactly does
1- for /r "C:\source" %%f in (*) do copy /y "%%f" C:\ReadyToExport
this line copies all files from source to another target folder the good thing is that this command copies all the files inside other subfolders from source and paste them into the folder C:\ReadyToExport without any subfolders.
2- del C:\ReadyToExport\*.pdf*
this command filters all the .pdf files because they are unnecessary
3-
for /f "delims=" %%i in ('xcopy "C:\ReadyToExport" C:\import /EXCLUDE:LogFile.log /S /E /D') do (
echo %%i >> C:\LogFile.log)
this command basically copies all files from "C:\ReadyToExport" into C:\import and writes the name of the recorded file in LogFile.log then the copied files will be excluded when the script runs again because I don't want to copy the files again if I already copied them before
and here is what I want to achieve:
I want to copy only modified files from the folder "C:\ReadyToExport" to the target C:\import but keep in mind that
the files in the target folder "C:\import" will be deleted but since the names of the files that have already been copied are registered in LogFile.log the files will be excluded and not copied again.
in another word: files in target file do not exist anymore but their names are written in LogFile
so is there any way to copy only modified ones? even though they don't exist in the target folder anymore? but their names are in LogFile.txt? can the script somehow write the last modified date in LogFile.txt near the file name? and then compare the date from the source? so it copies only files that have been changed and ignore all files that didn't?
p.s: using Xcopy, robocopy, etc is not a problem
any answer will be appreciated.
thnx
your method does, in fact, works so thank you so much not the way the I want with exclude:logfile.log
but this definitely worked:
robocopy C:\ReadyToExport\ C:\import /M /E
since it copies only the files that hast the attribute archivable checked in the settings.

Batch command to delete everything (sub folders and files) from a folder except one file

First of all, similar questions have been answered in past but not exactly the one I have. In some other solutions, hiding folders/files and changing attributes were suggested and I do not want this, unless there is no simpler way available. Also, I have tried the solution suggested here (and couple of others): MS-DOS command to delete all files except one.
But did not work for my need due to two reasons:
This also deleted the file, I did not want to.
This did not delete the sub-folders but only the files.
So, I have folder c:/users/data and in there, I have 5 folders and 6 files I want to delete everything except one which is web.config and to do that I run the batch file like this:
#echo off
for %%j in (C:\Users\data\*) do if not %%j == Web.config del %%j
pause
But when I run the batch file, this deletes all the files including web.config and also, does not delete any of the sub-folders and if I use the /d switch then it only deletes folders not files. How can I delete both files and folders?
Here is the way I would do it:
pushd "C:\Users\data" || exit /B 1
for /D %%D in ("*") do (
rd /S /Q "%%~D"
)
for %%F in ("*") do (
if /I not "%%~nxF"=="web.config" del "%%~F"
)
popd
The basic code is taken from my answer to the question Deleting Folder Contents but not the folder but with the del command replaced by a second for loop that walks through all files and deletes only those not named web.config.
Note that this approach does not touch the original parent directory, neither does it touch the original file web.config. The great advantage of this fact is that no attributes are going to be lost (for instance, creation date and owner).
Explanation
change to root directory by pushd; in case of failure, skip the rest of the script;
iterate through all the immediate sub-folders of the root by a for /D loop and delete them recursively by rd /S with all their contents;
iterate through the files located in the root by a standard for loop; use the ~nx modifier of the loop variable to expand base name (n) and extension (x) of each file, compare it with the given file name (if) in a case-insensitive manner (/I) and delete the file by del only in case it does not match (not);
restore former working directory by popd finally;
The main problems in your code are:
that you compare more that the pure file name with the prefedined name, so there is not going to be found any match.
you needed to use case-insensitive comparison, because Windows does not care about the case of file names for searching.
you did not put quotation marks around the comparison expressions, so you are likely going to receive syntax error messages, depending on what special characters occur in the file names.
that you are using the del command only which just deletes files; to remove directories, you needed to use rd also.
I'm not sure where the web.config file is stored or if there is more than one, so ...
Only one web.config file
Just lock the file (redirect the file as input) and remove anything else
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
<"web.config" rmdir . /s /q
popd
)
The code will
(pushd) Change to the target folder (we need to be sure this will remove information only from the intended place) setting it as the current active directory and locking it (we can not remove the current active directory). If the command can change to the folder then
(rmdir) Redirect the web.config as input to the rmdir command. This will lock the file so it can not be deleted until the command ends. The rmdir . /s /q remove anything not locked inside (and below) the current active directory
(popd) Cancel the pushd command restoring the previous active directory
Several web.config files in multiple folders
Following the approach (copy, clean, restore) pointed by #Dominique
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
for %%t in ("%temp%\%~n0_%random%%random%%random%.tmp") do (
robocopy . "%%~ft" web.config /s
robocopy "%%~ft" . /mir
rmdir "%%~ft" /s /q
)
popd
)
The code will
(pushd) Change to the target folder (we need to be sure this will remove information only from the intended place). If the command can change to the folder then
(for) Prepare a reference (a random name) to a temporary folder to use
(robocopy) Copy only the web.config files (and their folder hierarchy) from the source folder to the temporary folder
(robocopy) Mirror the temporary folder to the source folder. This will remove any file/folder not included in the temporary copy
(rmdir) Remove the temporary folder
(popd) Cancel the pushd command restoring the previous active directory
Once the web.config files are saved, as the files in the source will match those in the temporay folder, they will not be copied back with the second robocopy call, but any file/folder in source that is not present in the temporary folder will be removed to mirror the structure in the temporary folder.
I also managed to do it, very similar to #aschipfl
For /D %%k in (C:\Users\data) do (For /d %%m in ("%%k\*") do rmdir /s /q "%%m"
For %%m in ("%%k\*") do if not %%m == %%k\Web.config del /q "%%m")

how to copy files from one directory to other in batch command

I wish to copy a file with extension .dyn which is located in each subfolder of main folder(T15_finished). I wish to copy it into respective subfolder at other location(T15). I have created that location using xcopy command. Here, .dyn file is being copied successfully in respective subfolder in T15 folder(see below code). Now, I have a file which has extension as .dynain which is located in the same subfolder as .dyn. And .dynain file is also getting copied which i don't want.
Please see following code which i have created. Can anyone tell me whats wrong ?
#echo off
xcopy D:\Master\SPRINGBACK\CPW\T15_finished D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15 /t
xcopy /e D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15
pause
Short file names. If you do a dir /x in the folder containing the .dynain file, you will see the 8.3 filename generated for the file, and it will have .dyn extension.
If you know the extensions of the conflicting files, you can use robocopy with /xf switch to indicate the files (*.dynain) to exclude, or you can generate a exclude file to use with xcopy /exclude:file (see xcopy /? for a explanation)
Or, you can generate the list of files to exclude
(for /f "tokens=" %%a in (
'dir /s /b "D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn" ^| findstr /v /i /e /l ".dyn"'
) do #echo(%%~nxa)>excludedFiles.txt
xcopy /exclude:excludedFiles.txt /e D:\Master\SPRINGBACK\CPW\T15_finished\*.dyn D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15
Or (as posted by foxidrive), copy all and then delete the non needed files.
The short filename is being matched as well as the long filename. That is the reason.
A solution is to use another command to delete the files:
del /s "D:\Master\SPRINGBACK\FRESH_SPRINGBACK\CPW\T15\*.dynain"

Need Batch script to search and copy specific file from network drive

I am very new to batch scripting.
I need to write a batch script to search for a specific file(usually .zip or .7z extension) located on network drive directory(containing multiple folder and sub-folders with space in name) and copy the same to my local drive.
Also I need to copy a zip file containing "elf" keyword which will also be located in the same directory where my file is present.
For example:
Search file: abc.zip
Network drive:\abc.com\test
So basically I need to search for my file abc.zip in the network directory(including sub-folders) and if found copy the same to my local drive(say c:\Temp) and also I need to copy *elf* file to the same local directory.
Thanks in Advance.
#echo off
rem Prepare environment
setlocal enableextensions
rem Configure paths
set "source=\abc.com\test"
set "target=c:\test"
rem Change drive/path to source of files
pushd "%source%"
rem Recurse folders searching adecuated files and when found, copy to target
for /f "tokens=*" %%f in ('dir /s /b "abc.*z*" ^| findstr /i /e /c:".zip" /c:".7z"') do (
copy /y "%%~ff" "%target%"
if exist "%%~dpf\*elf*.zip" copy /y "%%~dpf\*elf*.zip" "%target%"
)
rem Return to previous drive/path
popd
rem Clean
endlocal
This will search the source folder hierarchy for indicated filename and an aproximate match based on file extension (.*z* matchs .zip, .7z and more), filters file extensions to only accept the cases needed (.zip and .7z) and copy the required files to target folder.
Have you considered using the Extended Copy Utility (xcopy)? Syntax is as simple as
xcopy "<directoryToCopyFrom>" "<directoryToCopyTo>" /C /S /D /Y /I
This will work assuming you're wanting to write a Windows batch script.
Searching for the "elf" string will be a bit trickier though. You might consider doing that using Java, and then call the batch file from the Java program.
for /d /r "drive:\abc.com\test" %%A in (*) do (
if exist "%%~A\abc.zip" copy "%%~A\abc.zip" "C:\Temp"
if exist "%%~A\*elf*" copy "%%~A\*elf*" "C:\Temp"
)

How to remove all folders of name x within a directory using cmd/batch file

I have a folder named x with a number of subfolders and files. I want to delete a folder named y that is present in x and all of it's subfolders. The said folder that has to be deleted may or may not contain any files. I believe i can do this using cmd or some kind of batch file but i am a command line new bi and can really use some help.
A simple thing would be to rd the folder's name, which works but i believe there are better ways than removing each folder individually.. like some loop that goes through all the folders.
Thanks
EDIT: Just to clarify, i have y (the folder that needs to be deleted) inside of x, and it can be in any of x's subfolders and at any level of depth. Also i am looking at answers and it may take some time for me to accept any answer. Please bear with me :)
Here is another solution for this commented to describe each part of the script:
#Echo OFF
REM Important that Delayed Expansion is Enabled
setlocal enabledelayedexpansion
REM This sets what folder the batch is looking for and the root in which it starts the search:
set /p foldername=Please enter the foldername you want to delete:
set /p root=Please enter the root directory (ex: C:\TestFolder)
REM Checks each directory in the given root
FOR /R %root% %%A IN (.) DO (
if '%%A'=='' goto end
REM Correctly parses info for executing the loop and RM functions
set dir="%%A"
set dir=!dir:.=!
set directory=%%A
set directory=!directory::=!
set directory=!directory:\=;!
REM Checks each directory
for /f "tokens=* delims=;" %%P in ("!directory!") do call :loop %%P
)
REM After each directory is checked the batch will allow you to see folders deleted.
:end
pause
endlocal
exit
REM This loop checks each folder inside the directory for the specified folder name. This allows you to check multiple nested directories.
:loop
if '%1'=='' goto endloop
if '%1'=='%foldername%' (
rd /S /Q !dir!
echo !dir! was deleted.
)
SHIFT
goto :loop
:endloop
You can take the /p out from in front of the initial variables and just enter their values after the = if you don't want to be prompted:
set foldername=
set root=
You can also remove the echo in the loop portion and the pause in the end portion for the batch to run silently.
It might be a little more complicated, but the code can be applied to a lot of other uses.
I tested it looking for multiple instances of the same foldername qwerty in C:\Test:
C:\Test\qwerty
C:\Test\qwerty\subfolder
C:\Test\test\qwerty
C:\Test\test\test\qwerty
and all that was left was:
C:\Test\
C:\Test\test\
C:\Test\test\test\
FOR /D /R %%X IN (fileprefix*) DO RD /S /Q "%%X"
Take care of using that...
for RD command:
/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
the FOR command is used to loop through a list of files or variables, the options are very easy to memorize, Directory only Recursively.
A problem common to this type of topics is that if there are instances of the target folder at several levels, most methods cause an error because when an high level folder is deleted, all folders below it disappear. For example:
C:\X\Y\subfolder
C:\X\Y\subfolder\one\Y
C:\X\Y\subfolder\two\Y
C:\X\Y\subfolder\three\Y
C:\X\test
C:\X\test\test
Previous example generate a list of 4 folders named Y that will be deleted, but after the first one is deleted the three remaining names no longer exist, causing an error message when they are tried to delete. I understand this is a possibility in your case.
To solve this problem the folders must be deleted in bottom-up order, that is, the innermost folder must be deleted first and the top level folder must be deleted last. The way to achieve this is via a recursive subroutine:
#echo off
rem Enter into top level folder, process it and go back to original folder
pushd x
call :processFolder
popd
goto :EOF
:processFolder
rem For each folder in this level
for /D %%a in (*) do (
rem Enter into it, process it and go back to original
cd %%a
call :processFolder
cd ..
rem If is the target folder, delete it
if /I "%%a" == "y" (
rd /S /Q "%%a"
)
)
exit /B
Although in this particular case the problems caused by other methods are just multiple error messages, there are other cases when this processing order is fundamental.
Make .bat with following:
del /q "C:\Users\XXX\AppData\Local\Temp\*"
FOR /D %%p IN ("C:\Users\XXX\AppData\Local\Temp\*.*") DO rmdir "%%p" /s /q

Resources