Creating a Batch to go through all folders on a share and move files - batch-file

Here is what I am attempting to do and if I can get your help it would be greatly appreciated!
Issue:
I want to create a script to do the following:
Go out to a network share where all account folders exist (2,400 folders with a 9-digit naming convention for account numbers, i.e folder name is 123456789).
Then go through a specific directory within the account folders that have a time stamp naming convention (i.e 123456789\Jan_29_2013_453pm).
Next, all folder structures are the same for all account folders EXCEPT the time stamped folder under the root (i.e 123456789`Jan_29_2013_453pm`\data).
Once being able to get through the time stamp folder there will be a set of folders that start off with a naming convention of media1, media2, media3, media4, media5, etc. that I need to access in order to move files.
I need to move a certain file from all media folders into media1. **There is an unknown amount of media folders for different account folders. Some may have 1 and other may have 50.
I need to run a test within the data folder (123456789\Jan_29_2013_453pm\data) to open a logfile.txt to see if a specific string exists at the end of the log (i.e item was successfully created as well as item has failed`).
If there is a SUCCESSFUL string in the logfile.txt, then go ahead and move all files from other media folders into media1. If a FAILURE string, then output the account folder name to a log file (output.txt) so I am aware which account folders failed (I would append the output as I will run this script multiple times).
The idea is to disregard account folders that have just a single media1 folder. Other account directories that have more than ONE media folder need to run a test against the log for SUCCESS or FAIL and depending on the string, to move a single file from all other media (media2,media3,media4,etc.) folders over to media1 unless FAILURE is read in the log.
I created a text file with all account folders on the share. I'm sure a FOR statement can be used against it. I'm also sure that a FOR statement can be used to go through the log in the "DATA" directory to look for the "SUCCESSFUL" or "FAILED" string.
The hard part I see is being able to get through the time stamped folder in order to get to the DATA directory.
THANKS AGAIN FOR ALL THE HELP!
#echo off
setlocal enabledelayedexpansion
:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.
echo Press ENTER to begin...
pause
echo.
goto :main
:main
cls
echo.
set /P acct=Please type the 9 digit account number you would like to restore:
set acctDir=X:\!acct!\
set acctDir2=media1\Setup\setup.exe /cd
set acctDir3=media1
set x=x:\!acct!\!userDir!
set sumLog="x:\!acct!\!userDir!\SummaryLog.txt"
set succ=finished
set log=c:\logs.txt
echo. Starting on !date! !time! on !Computername! >> !log!
echo.
echo The account number you selected is: !acct!
echo.
goto :user
:user
set /p answer=Is this correct (Y/N)?
echo.
if /i !answer!==y goto :yes (
) else (
echo.
echo Ok. Let's try again^^!
echo.
pause
cls
goto :main
)
)
:yes
set c=0
For /f %%a in ('dir !acctDir! /B /A:D') do (
set /a c+=1
echo !c! %%a
set dir!c!=%%a
)
echo.
set /p userIn="Select a directory [1-!c!]: "
set userDir=!dir%userIn%!
echo.
echo You selected !userDir! for your data retrieval.
echo.
goto :execute
:execute
echo.
echo The software will now be installed...
start !acctdir!\!userDir!\!acctDir2! >>!log!
:move
forfiles /p "!acctdir!\!userDir!\" /s /m *.ARC /c "cmd /c move #file !acctdir!\!userDir!\!acctdir3!"
goto
:string
findstr " .*!succ!" !sumLog!
if exist errorlevel 0 (
pause
goto :move
) else (
goto :eof
)
endlocal
goto :eof

Related

CMD to flatten a directory using cmd - but keeping files if the name occurs more than once [duplicate]

So, here's what I have: I created a small batch file to record the results of a ping test to a text file. What I want to do is run the batch file and move the results log to a specific folder on the Desktop automatically. Then, if the target filename exists, automatically rename accordingly. Meaning, if File1 exists, create File2, File3, so on and so forth. Here's what I have so far:
#echo off
color A
title Ping Test
:A
echo.
cls
ping google.com -n 4 > C:\Users\%username%\Desktop\pingresults.txt
cls
:Question
echo.
echo You can find the results in C:\Users\%username%\Desktop\pingresults.txt
echo Would you like to run this test again? (Y/N)
Set /p Choice=
if %choice% equ y goto :A
if %choice% equ n goto :Results
if %choice% neq y goto :Question
if %choice% neq n goto :Question
:Results
cls
echo Would you like to view the results of the test? (Y/N)
Set /p Choice=
if %choice% equ y goto :OpenResults
if %choice% equ n goto :Close
if %choice% neq y goto :Results
if %choice% neq n goto :Results
:Close
exit
:OpenResults
start C:\Users\%username%\Desktop\pingresults.txt
And the move batch file looks like this:
#echo off
echo.
cd C:\Users\Diesel\Desktop
move pingresults.txt PingResults\
if exist pingresults.txt ren pingresults.txt=+1
Exit.
I don't want to overwrite the existing file, but rename it in succession. I can't find any helpful articles anywhere using only batch files, they all say to use vbs or php, a language I'm not familiar with
To rename files to file1 [file2][...] and move it in a desktop folder:
#ECHO Off &SETLOCAL
FOR %%a IN (*.txt) DO CALL:processFile "%%~a"
goto:eof
:processFile
SETLOCAL
:loop
SET /a fileCounter+=1
SET "fileName=%~n1%filecounter%%~x1"
IF EXIST "C:\Users\%username%\Desktop\%fileName%" GOTO:loop
ECHO MOVE "%~1" "C:\Users\%username%\Desktop\%fileName%"
ENDLOCAL
goto:eof
Look at the output and remove the word echo before move if it looks good.
I have a pair of utility files that do this, so I can call from either command line, or another batch file. This manages several versions of the file in the same folder, and I would call it before moving your new file in.
Usage is:
archivefile 5 "c:\temp\songs" .txt [move]
Where 5 is the number of versions to keep.
The base file name in this example is "c:\temp\songs.txt"
and it creates (in c:\temp) 5 files: songs_1.txt songs_2.txt songs_3.txt songs_4.txt songs_5.txt
If you specify move it will move the original songs.txt otherwise it copies it.
Note, if you're using it from another batch file (which you'll probably want to), you need to use call or it won't return to your original batch file (both batch files will exit instead, which isn't what you want):
call archivefile 5 "c:\temp\songs" .txt
You need the pair of batch files to be either in the current directory, or on the windows path. Now I think about it, archivefile_b.bat could probably be a sub-routine within the main file instead, but it ain't broke, so I'm not going to fix it.
This is archivefile.bat:
#Echo off
rem archivefile.bat - keep a number of archives of a file
rem paramters: n rootfile extension [move|copy]
rem n = number of files to keep.
rem move|copy optional indicator to rename (move) the original file instead of copying it
rem archivefile 5 "c:\temp\songs" .txt [move]
rem
if "%3"=="" goto usage
set _af_n=%1
set _af_root=%2
set _af_ext=%3
set _af_move=copy
set _af_moveX=%4
if "%_af_moveX%"=="move" set _af_move=move
set _af_i=
set _af_j=
rem make sure that the first parameter (n) is numeric
set /A _af_n=%_af_n%
if "%_af_n%"=="0" echo Error: number of copies must be numeric (%1) & goto usage
if not exist %_af_root%%_af_ext% echo Error: cannot locate main file: %_af_root%%_af_ext% & goto error
rem remove the oldest file
if exist %_af_root%_%_af_n%%_af_ext% del %_af_root%_%_af_n%%_af_ext%
rem move up the remainder
for /L %%i in (%_af_n%, -1, 1) do call archivefile_b %%i %_af_root% %_af_ext%
rem copy the original
if "%_af_move%"=="move" goto moveIt
rem move not specified - make a copy
copy %_af_root%%_af_ext% %_af_root%_1%_af_ext%
goto moveCopyDone
:moveIt
rem need filename only for a rename
set _af_destfile=%_af_root%_1%_af_ext%
set _af_destfile=%_af_destfile:"=%
for %%i in (%_af_destfile%) do set _af_destfile=%%~ni%%~xi
ren %_af_root%%_af_ext% %_af_destfile%
:moveCopyDone
dir %_af_root%*%_af_ext%
goto done
:usage
echo usage: archivefile n rootfile extension
echo - n = number of archives to keep
echo - rootfile = the root filename
echo - extension = file extension
echo.
echo example:
echo archivefile 5 "c:\Documents and Settings\gregh\My Documents\Rescued document" .txt
goto done
:error
rem could maybe do something here? naa.
goto done
:done
This is archivefile_b.bat, which manages just one of the files:
rem #Echo off
rem archivefile_b.bat - helper for the archivefile routine
rem -- juggles ONE of the archive files.
rem paramters: n rootfile extension
rem n = the index to move from n to n+1
rem archivefile 5 "c:\temp\songs" .txt
rem therefore renames c:\temp\songs_5.txt to c:\temp\songs_6.txt
set _afb_n=%1
set _afb_root=%2
set _afb_ext=%3
rem make sure that the first parameter (n) is numeric
set /A _afb_n=%_afb_n%
if "%_afb_n%"=="0" echo Error: (archivefile_b) number of copies must be numeric (%1) & goto done
set /A _afb_j=%_afb_n%+1
rem define the file names
set _afb_fn=%_afb_root%_%_afb_n%%_afb_ext%
set _afb_fj=%_afb_root%_%_afb_j%%_afb_ext%
rem remove the quotes
set _afb_fn=%_afb_fn:"=%
set _afb_fj=%_afb_fj:"=%
rem can only supply a filename to the ren command (not path)
for %%i in (%_afb_fj%) do set _afb_fj=%%~ni%%~xi
rem do the rename now
if exist "%_afb_fn%" ren "%_afb_fn%" "%_afb_fj%"
:done

Batch Coding - Choose command not returning the correct answer

I am trying to create a batch file which has two options:
Create a series of folders with custom names (defined by variables inputted by the user)
OR
Create the same as before except also, once completed, automatically
copying all appropriate files to the appropriate folders in the
structure.
The idea is that with this batch file I could keep my film projects (As I am a freelance filmmaker working with my brother) in exactly the same folder structures across all 3 of our computers. AKA a uniform Project folder structure can be implemented with a simple double click and a few variables to fill in, while in the case of option 2 any files found on a specified SD Card are also moved to the appropriate folders within the structure.
The actual xcopy commands and mkdir commands etc. work exactly how they are supposed to.
Since the different computers will be allocating different drive letters depending on what is already attached to the computer before entering the SD Card into the card reader, I will never know what the drive letter of the SD Card will be (from which the footage and images will be loaded onto the computers).
For example:
One computer could have an external hard drive in (of which we have a few) at the time of the SD Card being plugged in, while another may have only the SD Card as an external device.
The code below is the complete .bat file including past code which I had tried but didn't work or needed to be excluded for some reason. I have some lines of code in comments so I know what I had tried in the past, these are obviously not meant to be used anymore.
:Menu
ECHO OFF
CLS
ECHO OFF
TITLE Saborknight Productions - Project Creator
ECHO.
ECHO ...............................................
ECHO PRESS the appropriate number to select your task, or 3 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Create Saborknight Default folder Hierarchy within a project folder
::(Disabled)ECHO 2 - Create Saborknight Default folder Hierarchy AND copy ALL files from SD Card to the appropriate folder
ECHO 3 - EXIT
ECHO.
ECHO WARNING - Option 2 will delete the files from the Recording Device automatically. Secure the device before proceeding!
ECHO.
ECHO.
CHOICE /c 123 /n
IF ERRORLEVEL 3 EXIT
IF ERRORLEVEL 2 GOTO :CREATE
IF ERRORLEVEL 1 GOTO :CREATE
::End of Menu
---------------------------------------------------------------------------------------------
:CREATE
::Creates DIR Folder Structure as per Saborknight Productions Standard
ECHO OFF
CLS
::Variables Descriptor
SET /P project_name=Enter the Project Name: || SET project_name=NothingChosen
If "%project_name%"=="NothingChosen" (
GOTO ERROR_PROJECT
) ELSE (
GOTO CREATOR
)
:ERROR_PROJECT
::If no Project Name is entered
ECHO Please enter the Project Name
GOTO CREATE
:CREATOR
::DIR Creator + Confirmation
::Videos DIR
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Footage
::Cut from above MKDIR -> \"Day 1"\%device_name%
::Images DIR
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Images\%device_name%
::Audio DIR -> Soundtracks
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\Soundtracks
::Audio DIR -> Recordings
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\Recordings
::Audio DIR -> Sound FX
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\"Sound FX"
::Premier Project DIR
ECHO OFF
MKDIR D:\Dropbox\"Project Files"\"%project_name%"
ECHO The Folder Structure has been created
ECHO.
ECHO.
ECHO What would you like to do next?
Echo.
ECHO 1 - View Created Folder Structure
ECHO 2 - Go to Menu
ECHO 3 - EXIT
::Choice is invisible
CHOICE /c 123 /n
IF ERRORLEVEL 3 EXIT
IF ERRORLEVEL 2 GOTO MENU
IF ERRORLEVEL 1 GOTO VIEW
::End of CREATE
---------------------------------------------------------------------------------------------
:COPY
::Creates DIR Folder Structure as per Saborknight Productions Standard + Copying/Moving Files from a selected SD Card connected to the computer
ECHO OFF
CLS
:COPY_PROJECT
::Project Variable Descriptor
SET /P project_name=Enter the Project Name: || SET project_name=NothingChosen
If "%project_name%"=="NothingChosen" (
GOTO ERROR_COPY_PROJECT
) ELSE (
GOTO COPY_DEVICE_NAME
)
::If True, Process continues
:COPY_DEVICE_NAME
::Device Name Variable Descriptor
ECHO.
SET /P device_name=Enter the Name of the Recording Device: || SET device_name=NothingChosen
If "%device_name%"=="NothingChosen" (GOTO DAMN_DEVICE) ELSE (GOTO DEVICE_DIR)
:DEVICE_DIR
::Device DIR Variable Descriptor
ECHO.
::Selecting the location of the SD Card of the Recording Device + Confirmation
ECHO Copy files from drive: E, F, G, H or I?
SET _drive=G
::SETLOCAL EnableDelayedExpansion
::CHOICE /c fgehi
::IF ERRORLEVEL 5 SET _drive=I
::IF ERRORLEVEL 4 SET _drive=H
::IF ERRORLEVEL 3 SET _drive=G
::IF ERRORLEVEL 2 SET _drive=F
::IF ERRORLEVEL 1 SET _drive=E
ECHO.
ECHO You have selected drive %_drive%:
ECHO.
::DIR Creator + Confirmation -> Only if Device Drive is successfully selected
::Videos DIR
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Footage\"Day 1"\"%device_name%"
::Images DIR
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Images\"%device_name%"
::Audio DIR -> Soundtracks
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\Soundtracks
::Audio DIR -> Recordings
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\Recordings
::Audio DIR -> Sound FX
ECHO OFF
MKDIR D:\"Movie Projects"\"%project_name%"\Audio\"Sound FX"
::Premier Project DIR
::ECHO OFF
::(Disabled for Testing)MKDIR D:\Dropbox\"Project Files"\"%project_name%"
ECHO.
CHOICE /c YN /m "Would you like files to be deleted automatically from the device? Press Y=Yes or N=No"
IF ERRORLEVEL 2 GOTO NO_DELETE
IF ERRORLEVEL 1 GOTO DELETE
:NO_DELETE
::No Deletion once Copied from Device
::For Copying Videos
ECHO.
ECHO Copying Videos
XCOPY %_drive%:\DCIM\ "D:\Movie Projects\"%project_name%"\Footage\"Day 1"\"%device_name%"\" *.MOV *.mp4 /V /-Y
::COPY %_drive%:\DCIM\ "D:\Movie Projects\"%project_name%"\Footage\"Day 1"\"%device_name%"\" *.MOV *.mp4
::ROBOCOPY %_drive%:\DCIM "D:\"Movie Projects"\"%project_name%"\Footage\"Day 1"\"%device_name%"\*" *.mov *.mp4 /mir /copy:DATO /np /eta /log+:"Log - Footage CopyOnly.txt" /nosd /nodd
PAUSE
::For Copying Images
ECHO.
ECHO Copying Images
XCOPY %_drive%:\DCIM\ "D:\Movie Projects\"%project_name%"\Images\"%device_name%"\" *.MOV *.mp4 /V /-Y
::COPY %_drive%:\DCIM\*.jpg;*.png;*.cr2 "D:\Movie Projects\"%project_name%"\Images\"%device_name%"\" /V /-Y
::ROBOCOPY %_drive%:\DCIM "D:\"Movie Projects"\"%project_name%"\Footage\"Day 1"\"%device_name%"" *.jpg *.png *.cr2 /copy:DATO /mir /np /eta /log+:"Log - Images Copy Only.txt" /nosd /nodd
PAUSE
GOTO SUCCESS_MSG
:DELETE
::Copying with Automatic Deletion once Copied
::For Copying and Deleting Videos
ECHO Copying and Deleting Videos
MOVE %_drive%:\DCIM\*.mov;*.mp4 D:\"Movie Projects"\"%project_name%"\Footage\"Day 1"\"%device_name%"\ /-Y
::ROBOCOPY %_drive%:\DCIM D:\"Movie Projects"\"%project_name%"\Footage\"Day 1"\"%device_name%" *.mov *.mp4 /mov /copy:DATO /np /eta /log+:"Log - Footage Copy Delete.txt" /nosd /nodd
PAUSE
::For Copying and Deleting Images
ECHO Copying and Deleting Images
MOVE %_drive%:\DCIM\*.jpg;*.png;*.cr2 D:\"Movie Projects"\"%project_name%"\Images\"%device_name%"\ /-Y
::ROBOCOPY %_drive%:\DCIM D:\"Movie Projects"\"%project_name%"\Images\"%device_name%" *.jpg *.png *.cr2 /mov /copy:DATO /np /eta /log+:"Log - Images Copy Delete.txt" /nosd /nodd
PAUSE
GOTO SUCCESS_MSG
:SUCCESS_MSG
::Only if all Copying/Moving and DIR Creation Processes are Completed Successfully
ECHO.
ECHO The Folder Structure has been created and files copied/moved
ECHO.
ECHO.
ECHO What would you like to do next?
Echo.
ECHO 1 - View Created Folder Structure
ECHO 2 - Go to Menu
ECHO 3 - EXIT
::Choice is invisible
CHOICE /c 123 /n
IF ERRORLEVEL 3 EXIT
IF ERRORLEVEL 2 GOTO MENU
IF ERRORLEVEL 1 GOTO :VIEW
:DAMN_DEVICE
ECHO.
ECHO Please enter the Device Name, Re-entering the Project Name
ECHO.
GOTO COPY
:ERROR_COPY_PROJECT
::If no Project Name is entered
ECHO.
ECHO Please enter the Project Name
ECHO.
GOTO COPY_PROJECT
ENDLOCAL
::End Of COPY
---------------------------------------------------------------------------------------------
:VIEW
ECHO OFF
CLS
TREE D:\"Movie Projects"\"%project_name%"
ECHo.
ECHO Press any key to return to Menu
ECHO.
PAUSE
GOTO MENU
::End of VIEW
The Problem
In this part of the code, the CHOOSE command wont choose the correct choice:
#ECHO OFF
CHOICE /c fgehi
IF ERRORLEVEL 5 SET _drive=I
IF ERRORLEVEL 4 SET _drive=H
IF ERRORLEVEL 3 SET _drive=E
IF ERRORLEVEL 2 SET _drive=G
IF ERRORLEVEL 1 SET _drive=F
Pause
ECHO.
ECHO You have selected drive %_drive%:
ECHO.
Pause
The Evidence of the Problem being a problem
I tested the Batch file on two separate machines (One by remote access so that the two screens lay side by side) and can be viewed here: Image of the Problem being a problem...
Apologies for the dirtiest code in history with a complete overuse of comments. This was supposed to be a one night project which has turned into a month long project and I still haven't solved it!
Even a programming friend of mine cannot explain why it wont work.
All help much appreciated in advance!!!
Also any alternative suggestions to complete the described tasks above are definitely welcome, I love learning new code!
Saborknight
Your program fail because IF ERRORLEVEL n ... "execute the command if the errorlevel is GREATER OR EQUAL than the number given", that is, you placed the IF commands in the opposite order. This works correctly:
#ECHO OFF
CHOICE /c fgehi
IF ERRORLEVEL 1 SET _drive=F
IF ERRORLEVEL 2 SET _drive=G
IF ERRORLEVEL 3 SET _drive=E
IF ERRORLEVEL 4 SET _drive=H
IF ERRORLEVEL 5 SET _drive=I
Pause
ECHO.
ECHO You have selected drive %_drive%:
ECHO.
Pause
May I suggest you a different, simpler method?
#ECHO OFF
SET option=0FGEHI
CHOICE /c fgehi
CALL SET _drive=%%option:~%ERRORLEVEL%,1%%
ECHO.
ECHO You have selected drive %_drive%:
ECHO.
Pause
As documented here: http://www.robvanderwoude.com/choice.php
By the way, in Windows NT 4 this won't work, since the SET command itself will set an errorlevel (usually 0)!
However, Windows NT makes it easy by storing the latest errorlevel in the environment variable ERRORLEVEL
This works for me:
#ECHO OFF
CHOICE /c fgehi
IF %ERRORLEVEL% EQU 5 SET _drive=I
IF %ERRORLEVEL% EQU 4 SET _drive=H
IF %ERRORLEVEL% EQU 3 SET _drive=E
IF %ERRORLEVEL% EQU 2 SET _drive=G
IF %ERRORLEVEL% EQU 1 SET _drive=F
Pause
ECHO.
ECHO You have selected drive %_drive%:
ECHO.
Pause
Unless you know the proper ritual to ask the Microsoft gods for forgiveness, I would recommend you stay away from batch, it is a lot of trouble.
Even PowerShell is much less of a hassle.

Prompting user to select directory in batch file

Issue:
I am attempting to have users select which folder to choose from within a specified directory and then add that folder to the address in order to execute a program within that directory.
For example, !acct! is the variable that I am using to ask the end user which account they want to access. This account is the starting or root folder for all other folders. The folder structure remains that same across all accounts EXCEPT for the second token of the folder. i.e) 123456789\*\program\setup\
The * is the folder where multiple folders exist that I would like the end user to choose from.
Once chosen, I would like the script to add that directory so that the program could be executed.
I thought by setting the variable acctDir=C:\Users\jdoe\Desktop\!acct!\ would allow me to add the acct number for the root directory, then run a FOR loop that would allow me to use a wild card in the set for /d %%i in ( !acctdir!*media1\setup ) do ( start !app! )
Any help would be greatly appreciated!
#echo off
setlocal enabledelayedexpansion
:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.
goto :main
:main
setlocal
set /P acct=Please type the 9 digit account number you would like to restore:
set acctDir=C:\Users\jdoe\Desktop\!acct!\
set app=setup.exe /cd
set log=c:\logs.txt
echo. Starting on !date! !time! on !Computername! >> !log!
echo.
echo The account number you selected is: !acct!
echo.
goto :user
:user
set /p answer=Is this correct (Y/N)?
echo.
if /i !answer!==y goto :yes (
) else (
echo.
echo Ok. Let's try again^^!
echo.
Pause
cls
goto :beginning
)
)
:yes
for /d %%i in ( !acctdir!*media1\setup ) do (
start !app!
)
endlocal
goto :eof
You could try something like the following:
set c=0
For /f %%a in ('dir !acctDir! /B /A D') do (
set /a c+=1
echo !c! %%a
set dir!c!=%%a
)
echo.
set /p uin="Select a directory [1-!c!]: "
set udir=!dir%uin%!
echo Selected - %udir%
This loops through a directory listing of !acctDir! and prompts the user to select a directory based on the number assigned to it.
!acctDir!\%udir% will then be the location of the directory.

Delete .txt files in subfolders using batch script [duplicate]

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

Append String to file name in dos Syntax Error Need

#ECHO off
title Rename Script
set dir1=%1
set STR=%2
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
FOR %%n in (%dir1% *.*) DO (
ren %%n %STR%%%n
echo %STR%%%n)
echo done
pause
C:>yogesh>LDK.bat C:\yogesh app
OUTPUT:
Running Rename Script for STR=app
The syntax of the command is incorrect.
appC:\yogesh
appa3dapi.dll
appHLTV-Readme.txt
apphltv.cfg
appkver.kp
applanguage.inf
appLDR.bat
appMp3dec.asi
appMss32.dll
appMssv12.asi
appMssv29.asi
appTrackerNET.dll
The batch file cannot be found.
C:\yogesh>
There are few issues with this script:
" The syntax of the command is incorrect." I do not know where is the problem in script.
How to get the count of number of files renamed ?
Files get renamed into the directory where the .bat file resides I want to rename the files in specified folder as argument in variable dir1
Please let me know if you need more information.
Here is a solution without using CD. You needed to put a \ between your dir1 variable and *.* instead of a space. You needed quotes to protect against spaces in names. Use FOR variable modifiers ~nx to get just the name and extension (removes any drive and path info). Finally, use SET /A to perform math.
#ECHO off
title Rename Script
set "dir1=%~1"
set "STR=%~2"
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
set cnt=0
FOR %%F in ("%dir1%\*.*") DO (
ren "%%F" "%STR%%%~nxF"
echo %STR%%%~nxF
set /a cnt+=1
)
echo %cnt% files were renamed.
echo done
pause
Here you go:
#ECHO off
title Rename Script
set /A count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
set /p STR=choose a start-string:
echo Running Rename Script for STR=%STR%
FOR %%n in (*.*) DO (
ren "%%n" "%STR%%%n"
echo "%STR%%%n"
set /A count+=1)
echo count %count%
echo done
pause
we can save the current path in OLDDIR and then change the path to the one the user gave, at the end of the script we'll go back to OLDDIR using CD
you need to set the counter with /A
UPDATE for dbenham:
A small proof :)) that it worked (for me) with filenames that contains spaces:

Resources