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.
Related
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
Hi have written a batch file to delete files and folders of a specified location
all is fine but the issue is that when there is no such F: drive in the machine then
the batch file delete the content of the folder where it has been kept .
Can any one help to modify the batch file and to write a condition to check wether that drive is present or not
My batch file
set folder="F:\PortalViewState"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
pushd "F:\PortalViewState" 2>nul &&( rmdir . /s /q & popd )||(echo Folder not present)
Change drive and active directory to the target folder, if no failure, then remove anything inside it (the folder can not be deleted as it is the active directory) and return to the previous active directory
#ECHO Off
SETLOCAL
pushd
set folder="F:\PortalViewState"
cd /d %folder% 2>nul
ECHO ERRORLEVEL=%errorlevel%
IF "%cd%"==%folder% (ECHO Switched to %folder%) ELSE (ECHO failed to switch to %folder%)
set folder="U:\sourcedir"
cd /d %folder% 2>nul
ECHO ERRORLEVEL=%errorlevel%
IF "%cd%"==%folder% (ECHO Switched to %folder%) ELSE (ECHO failed to switch to %folder%)
POPD
GOTO :EOF
This shows you two ways.
The surrounding pushd/popd simply saves and restores my test directory.
The u:\sourcedir directory exists on my system, so I get errorlevel=0 and a switched message. F: does not exist, so I get an errorlevel=1 and failed message.
The 2>nul suppresses the error message when the destination drive does not exist.
you don't need to pushd %folder%
read help rd and then, simply
rd /s /q "f:\portalviewstate"
Or, check that it exists or not and act accordingly
if not exist %folder% goto :somepart
in the bat file I got a simply command like :
xcopy "C:\Users\me\Documents\ApplyPatchBat" "C:\Users\me\Desktop\Test\" /S/E/K
This does the job where it will copy all the files including files inside subfolders. I know you can add /y to make it auto overwrite.
How ever I want to create an statement if this file that we are copying exist in the destination folder, copy the one in destination folder to a backup folder.
I wonder there is any IF statement I can add to after the command to detect if the file is existing? Or maybe an error level check when its asking do I want to overwrite? P.S. This is for applying new patches to a program, where there are many layers of folders, that's why I use the /S/E/K in xcopy.
xcopy itself can't backup beforehand, but with output from xcopy and a bit of for loop magic you can make this happen
#echo off
setlocal ENABLEDELAYEDEXPANSION
set source="C:\Users\me\Documents\ApplyPatchBat"
set target="C:\Users\me\Desktop\Test\"
rem /l = list only, /u = already existing, /y = yes to replace
rem /f = display full source and destination file names, /c = continue on errors
rem /s = subdirectories, /k = keep attributes
rem split the strings at ->, we're only interested in the part after ->
for /f "usebackq tokens=1,* delims=>" %%a in (`xcopy %source% %target% /l /u /y /f /c /s /k`) do (
set file=%%b
rem ignore lines without a destination, e.g. 15 file(s) copied
if x!file! neq x (
rem remove the leading space, original string is source -> destination
set file=!file:~1!
for %%f in ("!file!") do (
if not exist %%~dpf\backup\* md %%~dpf\backup
rem only backup if not already backed up
if not exist %%~dpf\backup\%%~nxf move %%f %%~dpf\backup
)
)
)
xcopy %source% %target% /y /c /q /s /k
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
I have about 250 files that I need to move to a specific folder. The problem is that folder only have the partial name of the files.
For example, I need to move file "12345.txt" to folder "12345 - hello" as each folder starts by the actual file name.
Can I do this in a batch file in DOS?
Thank you.
Assuming Windows, it's actually not hard:
#echo off
rem loop over all files
for %%f in (*) do call :process "%%f"
rem this is necessary to avoid running the subroutine below
rem after the loop above ended
goto :eof
rem subroutine that gets called for every file
rem this finds the first matching folder and moves the file there
:process
rem the /d loops over all directories - the mask ensures that
rem the directory name starts with the given file name (without
rem extension)
for /d %%d in ("%~n1*") do (
echo Moving "%~1" to "%%d" ...
move "%~1" "%%d"
rem Return since the file was moved already
goto :EOF
)
Can also be found in my SVN repository.