I have to delete files from a sub folder with a same name. My file path is like as follows.
d:\test\test1\archive\*.txt
d:\test\try\archive\*.txt
d:\test\model\archive\*.txt
I tried deleting using del command in batch script.
But there are more than 100 folders with in the folder "test". So it is very difficult to use del for each and every path.
Except for the parent folder name of "archive" folder, everything remains the same for all the paths. So I guess there might be some easy way to delete the files using batch script.
Can anyone guide me whether there is any easy way to delete the files using batch script? Or i have to repeat del for all 100 folders?
You can use the /s switch for del to delete in subfolders as well.
Example
del D:\test\*.* /s
Would delete all files under test including all files in all subfolders.
To remove folders use rd, same switch applies.
rd D:\test\folder /s /q
rd doesn't support wildcards * though so if you want to recursively delete all subfolders under the test directory you can use a for loop.
for /r /d D:\test %a in (*) do rd %a /s /q
If you are using the for option in a batch file remember to use 2 %'s instead of 1.
Use powershell inside your bat file
PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse
You can also exclude from removing some specific folder or file:
PowerShell Remove-Item C:/* -Exclude WINDOWS,autoexec.bat -force -recurse
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
#echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder.
*Remember when putting the base path in, the format does not include a '\' on the end.
e.g.
d:\test
c:\temp
Hope this helps
I had to complete the same task and I used a "for" loop and a "del" command as follows:
#ECHO OFF
set dir=%cd%
FOR /d /r %dir% %%x in (archive\) do (
if exist "%%x" del %%x\*.txt /f /q
)
You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.
These are the options for "for" command:
/d For directories
/r For recursive
These are the options for "del" command:
/f Force deletes read-only files
/q Quiet mode; suppresses prompts for delete confirmations.
del parentpath (or just place the .bat file inside parent folder) *.txt /s
That will delete all .txt files in the parent and all sub folders. If you want to delete multiple file extensions just add a space and do the same thing. Ex. *.txt *.dll *.xml
Related
can someone please help how to find specific folders with size 0 under directory using batch? thank you.
there are many folders in a parent folder, some of them have files inside and some folder are empty. I'd like to find out the name of the empty folders using batch file. can someone help? thanks
This script scans the target folder and returns the UNC paths of all empty subfolders within the target folder.
#echo off
setlocal EnableDelayedExpansion
REM This script scans the target folder and returns the UNC paths of all empty subfolders within the target folder.
title Looking for empties, please wait!
cd "%~dp0"
cls
if "%~1" == "" (
echo ERROR: No folder was specified! You gotta tell me where to look for empties!
echo Please drag-and-drop a folder onto the icon for this script.
pause
exit /b
)
if not exist "%~dpn1" (
echo ERROR: The folder you told me to scan doesn't seem to exist!
pause
exit /b
)
set "target=%~dpn1"
echo Scanning: %target%
echo.
REM Grab each subfolder for checking.
for /f "tokens=*" %%a in ('dir "%~dpn1" /s /b /a:d') do (call :checkForBlanks "%%a")
echo.
echo Done.
title Done.
pause
exit /b
:checkForBlanks
REM We've been given a folder. We must check if it's empty.
set "folder=%~1"
set "scanned=!folder:%target%=!"
title Looking for empties: %scanned:&=^&%
set exist=
for /f %%a in ('dir "%~1" /b') do (set "exist=%%a" & goto :found)
:found
if "%exist%" == "" echo EMPTY: %scanned:&=^&%
goto :eof
The following batch-file idea, which leverages powershell may provide the information you require.
I say, may, because you've not clarified what you deem to be an empty subfolder, or folder with size 0.
The following single line batch file example should work regardless of the installed powershell.exe version:
#(For /F "Delims=" %%G In ('%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP "(GCI -Rec|?{$_.PSIsContainer -Eq $True})|?{$_.GetFileSystemInfos().Count -Eq 0}|Select -Exp FullName" 2^>NUL')Do #Echo/%%G)&Pause
If you're using a more up to date version of powershell.exe, perhaps the following example may be preferable for you:
#(For /F "Delims=" %%G In ('%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP "GCI -AD -S|?{$_.GetFileSystemInfos().Count -Eq 0}|Select -Exp FullName" 2^>NUL')Do #Echo/%%G)&Pause
Both examples are designed to recurse from the current directory, if you wish to insert the base directory directly into the for loop then use it just after GCI in whichever example you choose, (preferable enclosed between single straight quotes)
I try to write a script that can monitor a folder H:\Start and copy a new subfolder with its files in H:\Start to new location H:\Target. The script should store the copied folder and files in a text file.
Each time the script starts new and monitors H:\Start, it should check the text file and copy only those subfolders which are not yet included in the text file because copied already before.
I was searching the world wide web for examples, but could not really find a starting point. Any help would be nice.
I have so far not working good :)
#echo off
setlocal EnableDelayedExpansion
pushd %1
for /D %%d in (“H:\Start\*.*”) do set n=!n!;%%d
if defined n echo %n:~1% > C:\Desktop\list.txt
popd
endlocal
for /f %%i in (C:\Desktop\list.txt) do not (
xcopy /d /s H:\Start H:\Target > C:\Desktop\list.txt >nul 2>&1
)
I suggest using:
%SystemRoot%\System32\xcopy.exe H:\Start H:\Target /C /H /I /K /M /Q /R /S /Y >nul
For information about all those parameters of xcopy open a command prompt window and run there xcopy /? to get help of this command displayed which explains all those parameters.
The important one is /M which selects for copying process just files with archive attribute set and which removes the archive attribute on each file in H:\Start after copying the file. This avoids that a once copied file is copied once more as long as not modified in H:\Start since last copy.
If you want to log all copied files into a text file, I suggest using:
%SystemRoot%\System32\xcopy.exe H:\Start H:\Target /C /F /H /I /K /M /R /S /Y >>C:\Desktop\list.txt
The names of the copied files are with this command line appended to text file C:\Desktop\list.txt
The following commented batch code works with directory lists as asked for.
#echo off
rem Define source and destination directory as well as
rem the names of the used list files each with full path.
setlocal EnableExtensions
set "Source=H:\Start"
set "Destination=H:\Target"
set "MainDirList=C:\Desktop\list.txt"
set "CurrentList=%Temp%\CurrentList.tmp"
set "ExcludeList=%Temp%\ExcludeList.tmp"
set "FinalDoList=%Temp%\FinalDoList.tmp"
rem Write the names of all subdirectories found in source
rem directory into a list file in directory for temporary files.
dir /AD /B "%Source%">"%CurrentList%"
rem Check if list file is not empty because of no subdirectories.
call :CheckEmpty "%CurrentList%"
if %FileIsEmpty% == 1 (
echo No directories in %Source%
goto EndBatch
)
rem Start copying the directories if there is no main list file
rem from a previous execution of this batch file or the main list
rem file was deleted intentionally to force copying all again.
if not exist "%MainDirList%" goto CopyDirectories
rem Start copying also if main list file is an empty file.
call :CheckEmpty "%MainDirList%"
if %FileIsEmpty% == 1 del "%MainDirList%" & goto CopyDirectories
rem Search in main list for lines matching completely lines in current
rem list with ignoring case and write the found lines into an exclude
rem list file as those directories were copied already before.
%SystemRoot%\System32\findstr.exe /I /L /X /G:"%CurrentList%" "%MainDirList%" >"%ExcludeList%"
rem Copy all directories if no line in current list is found in main list.
if errorlevel 1 goto CopyDirectories
rem Get all lines from current list not listed also in exclude list.
%SystemRoot%\System32\findstr.exe /B /I /L /V /G:"%ExcludeList%" "%CurrentList%" >"%FinalDoList%"
rem Replace the current list with the reduced final list.
move /Y "%FinalDoList%" "%CurrentList%"
rem Check if remaining current list is not empty because
rem all subdirectories copied already before.
call :CheckEmpty "%CurrentList%"
if %FileIsEmpty% == 1 (
echo Copied already before all directories in %Source%
goto EndBatch
)
:CopyDirectories
rem Copy each directory in remaining current list file.
for /F "usebackq delims=" %%D in ("%CurrentList%") do (
echo Coping %Source%\%%D
%SystemRoot%\System32\xcopy.exe "%Source%\%%D" "%Destination%\%%D" /C /H /I /K /Q /R /S /Y >nul
)
rem Append the list of copied directories to main list file.
type "%CurrentList%">>"%MainDirList%"
goto EndBatch
:CheckEmpty
rem This little subroutine just checks if size of a list file is 0.
if %~z1 == 0 ( set "FileIsEmpty=1" ) else ( set "FileIsEmpty=0" )
goto:EOF
:EndBatch
rem Delete all not further needed listed files and environment variables.
del "%ExcludeList%" 2>nul
del "%CurrentList%"
endlocal
This batch file should work for the FTP folder mounted as drive on Windows. It does not depend on attributes or timestamps. It uses explicitly only the names of the directories in H:\Start. It also does not check which directories exist already in H:\Target. Therefore it is possible to delete a directory in H:\Target if not interested in and the deleted directory will be nevertheless not copied once again from H:\Start as long as the deleted directory is not also removed from main list file.
For details on parameters used on findstr run in a command prompt window findstr /? and read the entire help output into the window.
Thanks for this question as this was really an interesting batch coding task.
You don't need to store anything, you can use
xcopy /d /s h:\start h:\target
/D:mm-dd-yyyy
Copy files changed on or after the specified date.
If no date is given, copy only files whose
source date/time is newer than the destination time.
but if you need a list of the files you can just use a redirection :
xcopy /d /s h:\start h:\target > logfile.txt
I have multiple files that I will write to within a temp folder. I call a batch file to either copy or move them:
#ECHO OFF
move /y %1 %2
EXIT
#ECHO OFF
xcopy /A %1 %2
EXIT
How would I call a batch file to check if all of the files have finished copying and there are no other files remaining? Then I would like to delete the folder.
**EDIT:
I figured out by just using a loop to continuously call rmdir will work fine
#ECHO OFF
:loop
rmdir %1
if EXIST %1 (
goto loop
)
EXIT
This works for you....
#echo off
REM Copy all the files from source to target first
xcopy /s source_directory target_directory
REM Check if there are any files of any type inside source_directory,if YES move it to destination and if NOT then delete the directory
dir /b /a "source_directory\*" | >nul findstr "^" && xcopy /s source_directory target_directory || rd <source_directory>
Note addition of /a option to enable finding of hidden and system files/folders.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete files in subfolder using batch script
I have to delete .txt files from a sub folder (with same name). My filepath is like as follows.
d:\test\test1\archive*.txt
d:\test\try\archive*.txt
d:\test\model\archive*.txt
I tried "del" command to delete the ".txt" files in above paths. But there are more than 100 folders in the folder "test". So it is very difficult to use "del" for each and every path.
Except the parent folder name of "archive" folder, everything remains the same for all the paths. So I guess there might be some easy way to delete the files using batch script.
Can anyone guide me whether there is any easy way to delete .txt files using batch script Or I have to repeat "del" for all 100 folders?
del /s *.txt
hope it helps.All the best mate
del /s *.txt will delete all TXT files in all subfolders of current working directory.
(But use that command carefully - wrong parent directory and you are throwing away all textfiles on your computer :) )
Edited
del /s d:\test\archive\*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
#echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder.
*Remember when putting the base path in, the format does not include a '\' on the end.
e.g.
d:\test
c:\temp
Hope this helps
I need a batch file that prompts the user for a file path, and the first 3 letters in the folder name. Then the batch goes and deletes all the folders and files in the folders with these 3 letters, but keeps the folder starting with the 3 letters. I got a batch file that deletes all files in folder and sub-folders, but I also need it to delete the sub-folders. Here was my code for deleting all files:
#echo off
set /p filepath=Path to Main Directory:
set /p string=First Letters of Sub-Folders to be Cleansed:
FOR /D %%G in ("%filepath%\%string%*") DO del "%%G\*.*" /q /s
echo Done
pause
Then I tried a lot of different ways to also delete sub folders of %%G. I got as far where it names the sub folders of %%G here:
#echo off
set /p filepath=Path to Main Directory:
set /p string=First Letters of Sub-Folders to be Cleansed:
FOR /D %%G in ("%filepath%\%string%*") DO for /r /d %%i in (%%G\*) do del "%%G\*.*" /q && echo %%i
echo Done
pause
But when I try to add && rd /s /q %%i at the end it says file and path not found.
No need to recursively look for folders in your "exp1" folder. You can simply use FOR /D to list the child folders and then use RD /Q /S to remove the entire folder hierarchy rooted on each child. Also, since all the child folders are being removed anyway, there is no need to do a recursive file delete.
#echo off
set /p filepath=Path to Main Directory:
set /p string=First Letters of Sub-Folders to be Cleansed:
for /d %%G in ("%filepath%\%string%*") do (
del "%%G\*" /q
for /d %%F in ("%%G\*") do rd /s /q "%%F"
)
echo Done
pause