How to do while loop in windows batch - batch-file

I wrote a windows batch script to check and move files to another directory based on the list I put in a notepad file named list.txt. But I have no idea that how to set the while-loop. Only to jump out of the subroute when the condition fulfill.
In C Programming, we could write like this by setting a while-loop direcly. But seems in windows batch is quite different.
All I want is like this:
Directory A:
1. A.txt
2. B.txt
3. list.txt (By line sequential with filename want to move)
4. process.bat
Directory B:
None of files (Then move a file by order of line set in list.txt) OR
A.txt (If already existed a text file in directory, process.bat will pause before A.txt disappear)
Process.bat
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
if exist D:\DirectoryA\*.txt (
echo %time% >> D:\AutoLog\Log.txt
echo Previous job did not finished yet. >> D:\AutoLog\Log.txt
Timeout /t 30
echo.
)
set name=%*
if exist %name%.txt (
echo %time% >> D:\AutoLog\Log.txt
echo File found and processing %name%.txt now... >> D:\AutoLog\Log.txt
copy "%~dp0\%name%.txt" "D:\DirectoryB"
echo Transfer %name%.txt completed!! >> D:\AutoLog\Log.txt
echo. >> D:\AutoLog\Log.txt
Timeout /t 790
echo.
echo ==============================================================
)
:eof
Please guide me to finish the script by using a while-loop method. Thanks

I change some script sequence and it works now.
#echo off
:readline
for /f "tokens=*" %%a in (list.txt) do call :processline %%a
goto :eof
:processline
set name=%*
if exist C:\Test2\*.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo Previous job did not finished yet. >> C:\Test2\Log.txt
Timeout /t 5
echo.
echo. >> C:\Test2\Log.txt
goto :processline
)
if exist %name%.txt (
echo %date% %time% >> C:\Test2\Log.txt
echo File found and processing %name%.txt now... >> C:\Test2\Log.txt
copy "%~dp0\%name%.txt" "C:\Test2"
echo Transfer %name%.txt completed!! >> C:\Test2\Log.txt
echo. >> C:\Test2\Log.txt
Timeout /t 10
echo.
echo ==============================================================
)
:eof

This will copy as well as count the number of lines from your text file..
# echo off
:TextPath
cls
set /p Input=#1 Enter the full path of the text file :
set /p Source=#2 Enter the full path of Source :
set /p Target=#3 Enter the full path of Destination :
:choice
set /P c=Ready to Continue[Y/N]?
if /I "%c%" EQU "Y" goto :Yes
if /I "%c%" EQU "N" goto :No
goto :choice
:Yes_Local
for /f "delims=" %%i in (%Input%) do echo f| xcopy /f /y "%Source%\%%i" "%Target%\%%i"
for /f %%C in ('Find /V /C "" ^< %Input%') do set Count=%%C
msg * No of Lines executed= %Count%
exit
:No
cls
color e
echo Redirecting to Main....
PING 127.0.0.1 -n 2 >NUL
cls
echo Please wait
PING 127.0.0.1 -n 4 >NUL
goto TextPath

Related

Log contents of text file before deleting

My script isn't logging the contents of run.txt to log.txt
I've tried to remove the delete command to see if it was deleting it too quickly and therefore couldn't log. But that wasn't the case.
What should I change?
#ECHO OFF &setlocal
SET File=run.txt
type %File%
for /f "tokens=*" %%A in (%File%) do (echo >> log.txt)
del "%File%" /s /f /q > nul
pause
Here is a very simple way to do the task you are requiring.
#echo off
REM Will only grab the first line of the file
set /p file=<run.txt
REM For the last line use a for loop
for /f "tokens=*" %%a in (%file%) do set last_line=%%a
(
echo %file%
)>>log.txt
del /f %file% >nul
If not %errorlevel% equ 0 (
ECHO ERROR - %errorlevel%
pause
exit /b
)
ECHO Success!
timeout /t 003
exit /b %errorlevel%
EXPLANATION
set /p is for set prompt. For more information you can use set /? in your CMD window or check out this site.
I wish I could speak more on what < does, but what it is doing here is piping the content of run.txt to our variable.
Then we echo out our variable to our log file with (ECHO This is our %file%)>>destination
>> is to append where > is to overwrite the file.
(
echo %file%
echo.
)>>%file%
Checking for an error is probably unnecessary, but I believe it is a good habit to build on which is what I am trying to do with that If not %errorlevel% statement.
No error? We Success and timeout ourselves for xxx seconds.
Try:
#ECHO OFF &setlocal
SET "File=run.txt"
type "%File%" >> "log.txt" && (del "%File%" /f > nul)
pause

how to compress multiple folders into one with batch file

i have a batch file to compress one folder and rename it with date & time and it's working well.
now i need same file to compress more than one folder into one compressed rar file.
here is my batch:
#echo off
echo STARTING BACKUP...
echo %date% %time%
echo+
:: variables
set src=D:\test
set dest=D:\Backups
set filename=%DATE:/=-%_%TIME::=-%
set filename=%filename: =%
Set Rar=%ProgramFiles%\WinRar\WinRAR.exe
"%Rar%" a -m5 -ed -pEltyar -r %dest%\%filename%.rar "%src%"
echo Backup Completed!
#pause
You can try something like this :
#echo off
Title Compress multi-folders in one with Winrar
Mode 70,5 & color 0A
echo STARTING BACKUP...
Call :GetFileNameWithDateTime
echo %filename%
:: variables
set src="D:\test1","D:\test2"
set dest=D:\Backups
If not exist "%dest%" MD "%dest%"
Set Rar=%ProgramFiles%\WinRar\RAR.exe
for /f "delims=," %%i in ('echo %src%') do (
"%Rar%" a -inul -m5 -ed -hpEltyar -r "%dest%\%filename%.rar" "%%~i"
)
If "%errorlevel%" EQU "0" (
echo(
echo Backup Completed Successfully !
) Else (
echo( & color 0C
echo There was an error occured !
)
Timeout /T 10 /nobreak>nul & exit
::*********************************************************************************************
:GetFileNameWithDateTime
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set "MyDate=%%x"
set "filename=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%"
exit /b
::*********************************************************************************************

Talking batch AI (that learns) but I have one issue

When i use it, it will only speak when i teach it another word, i can't get it to speak a specific answer in the directory, do you guys have any opinions on how to go about fixing this, i'm stumped..
#ECHO OFF
#mode con cols=55 lines=10
if not exist data.txt echo.>data.txt
:begin
set /p text="Talk: "
for /f "tokens=1,* delims=#" %%i in (data.txt) do (
if /i "%text%"=="%%i" (
echo Visu: %%j
goto begin
)
)
:Learn
echo --- I don't know that.
set /p answer=--- What would be a good answer to '%text%'?
echo %text%#%answer%>>data.txt
echo Visu: thank you
goto Aye
:Aye
echo set speech = Wscript.CreateObject("SAPI.spVoice") >> "temp.vbs"
echo speech.speak "%answer%" >> "temp.vbs"
start temp.vbs
pause
del temp.vbs
goto begin
Make Aye a subroutine/function you can call with the text to speak.
In a called sub the first argument is %1
#ECHO OFF
mode con cols=55 lines=10
if not exist data.txt Type Nul >data.txt
:begin
cls& Echo Talk to Visu
set "text=" & set /p text="Talk: "
if not defined text exit /B
for /f "tokens=1,* delims=#" %%i in (data.txt
) do if /i "%text%"=="%%i" Call :Aye "%%~j" & Goto :begin
:Learn
echo --- I don't know that.
echo --- What would be a good answer to '%text%'
set /p answer=?
echo %text%#%answer%>>data.txt
Call :Aye "%answer%"
goto :begin
:Aye
echo Visu: %~1
echo Visu: thank you
echo set speech = Wscript.CreateObject("SAPI.spVoice") > "temp.vbs"
echo speech.speak "%~1" >> "temp.vbs"
cscript //Nologo temp.vbs
Timeout /T 3 /Nobreak >Nul
del temp.vbs
goto :Eof
replace start temp.vbs with cscript /nologo temp.vbs.
And probably you want
echo set speech = Wscript.CreateObject("SAPI.spVoice") > "temp.vbs"
(> instead of >>) to overwrite the file every time?

How do I make a batch log file?

How do I make a log file from this code. This has been answered a ton, but this file is huge and I want a simple log file. As you see I also tried to add a log file names RandomNamesLog.log. See if the output goes there.
I want all the code to be outputted into the log file, with error messages and confirm messages, like removing the #ECHO OFF value.
If you need more on what I want, please tell me.
#ECHO OFF
SETLOCAL EnableDelayedExpansion for /F "tokens=1,2 delims=#" %%a in
('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do ( set
"DEL=%%a" )
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
ECHO.
REM Randomly renames every file in a directory.
SETLOCAL EnableExtensions EnableDelayedExpansion
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET PrependOnly=0
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "__Translation.txt" is in the same
folder.
REM If you delete the translaction file, you will not be able to undo
the changes!
SET Undo=0
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET TranslationFile=_TranslatonData.txt
SET LogFile=_RandomNamesLog.log
IF NOT {%Undo%}=={1} (
REM Rename files
ECHO You are about to randomly rename every file in the following folder:
ECHO %~dp0
ECHO.
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
ECHO Type "OK" to continue.
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Aborting.
GOTO :EOF
)
ECHO Original Name/Random Name > %TranslationFile%
ECHO ------------------------- >> %TranslationFile%
FOR /F "tokens=*" %%A IN ('DIR /A:-D /B') DO (
IF NOT %%A==%~nx0 (
IF NOT %%A==%TranslationFile% (
SET Use=%%~xA
IF {%PrependOnly%}=={1} SET Use=_%%A
SET NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!
ECHO %%A/!NewName!>> %TranslationFile%
RENAME "%%A" "!NewName!"
ECHO ----------------------------------------------------- >> %TranslationFile%
ECHO Designed by Trevor T | UltimateGuidesPro.blogspot.com >> %TranslationFile%
ECHO. >> %TranslationFile%
ECHO WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING! THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION! >> %TranslationFile%
ECHO +---------+
ECHO | Credits |
ECHO +---------+
Echo.
ECHO Original Random Names script created by
call :colorEcho 0a "Jason Faulkner"
call :colorEcho 0a "HowToGeek.com"
ECHO ---------------------------------------
ECHO Script created by
call :colorEcho 0a "Trevor T"
ECHO -------------------------------------------
ECHO Color Text system created by
call :colorEcho 0a "Visual Magic, user on Stack Exchange"
ECHO Type "Exit" to quit
GOTO :Exit
:Exit
SET /P Confirm=
IF /I NOT {!Confirm!}=={Exit} (
ECHO.
ECHO Please try again
GOTO :Exit2
Exit
:Exit2
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Please try again
GOTO :Exit
)
)
)
) ELSE (
ECHO UNDO MODE
IF NOT EXIST %TranslationFile% (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
PAUSE
GOTO :EOF
)
ECHO Undoing...
FOR /F "skip=2 tokens=1,2 delims=/" %%A IN (%TranslationFile%) DO RENAME "%%B" "%%A"
DEL /F /Q %TranslationFile%
ECHO Completed Undo!
Pause
)
Exit
REM This is the color text code. Don't touch this, unless you know a better way to use color text.
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
I have rewritten your script fixing all of the problems I could see and removing the pointless code to add colored text.
Test it to see if it works as it should adding whatever you think I've missed.
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
REM Randomly renames every file in a directory.
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET "PrependOnly=0"
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "_TranslationData.txt" is in the same folder.
REM If you delete the translaction file, you will not be able to undo the changes!
SET "Undo=0"
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET "TranslationFile=_TranslationData.txt"
IF "%Undo%"=="1" GOTO UNDOIT
ECHO You are about to randomly rename every file in the following folder:
ECHO %CD%
ECHO.
CHOICE /M "Do you want to continue "
IF NOT %ERRORLEVEL%==1 (
ECHO.
ECHO Aborting.
TIMEOUT -1
GOTO :EOF
)
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
(
ECHO ;Original Name/Random Name
ECHO ;-------------------------
FOR %%A IN (*) DO IF NOT "%%A"=="%~nx0" IF NOT "%%A"=="%TranslationFile%" (
SET "Use=%%~xA"
IF "%PrependOnly%"=="1" SET "Use=_%%A"
SET "NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!"
ECHO %%A/!NewName!
REN "%%A" "!NewName!"
)
ECHO ;-----------------------------------------------------
ECHO ;Designed by Trevor T ^| UltimateGuidesPro.blogspot.com
ECHO.
ECHO ;WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING!
ECHO ; THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION!
)>"%TranslationFile%"
ECHO +---------+
ECHO ^| Credits ^|
ECHO +---------+
ECHO.
ECHO Original Random Names script created by Jason Faulkner # HowToGeek.com
ECHO -------------------------------------------
ECHO Script created by Trevor T
ECHO -------------------------------------------
TIMEOUT -1
GOTO :EOF
:UNDOIT
ECHO UNDO MODE
IF NOT EXIST "%TranslationFile%" (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
TIMEOUT -1
GOTO :EOF
)
ECHO Undoing...
FOR /F "USEBACKQ TOKENS=1-2 DELIMS=/" %%A IN ("%TranslationFile%") DO REN "%%B" "%%A"
DEL /F "%TranslationFile%"
ECHO Completed Undo!
TIMEOUT -1
GOTO :EOF
Once you are happy with it edit your opening question explaining what it is you want to have in the log file and how you need it to look.
I use this. it seems to work.
It just starts a log file and maintains logs.
You can set logpath and logname (base name) then you call this create_logfile
It creates a semi-random log file.
Now you write to the set logfile
I'm not an advanced coder. Please feel free to correct:
#echo off
rem
echo %date% %TIME%
rem Log File Path
if "%logpath%" == "" set logpath=%~dp0
if "%logpath:~-1%" == "\" set logpath=%logpath:~0,-1%
rem Make log file name
if "%logname%" == "" set logname=log
set t=%TIME: =0%
set d=%DATE%
set logfilename=%logname%_%d:~12,2%%d:~4,2%%d:~7,2%%t:~0,2%%t:~3,2%%t:~6,2%.log
set t=
set d=
rem Test
echo full log file name = %logfilename%
echo find base log name = %logfilename:~0,-17%
echo log path = %logpath%
rem Logs to maintain
set /a dellog=5
rem Find file to delete
set var=
set /a cnt=0
set fltodel=
set fstfle=
for %%a in (%logpath%\%logname%*.log) do (
set var=%%a
call set /a "cnt+=1"
echo %%cnt%%| findstr /l "1" >nul && (call set fstfle=%%var%%)
echo %%cnt%%| findstr /l "%dellog%" >nul && (call set fltodel=%%fstfle%%)
)
rem Delete old log
echo file to delete %fltodel%
if exist %fltodel% (del /q %fltodel%) else (echo "%fltodel%" does not exist. nothing to delete.)
echo tryed to delete
rem Create Log File and logfile attribute
set logfile=%logpath%\%logfilename%
if exist %logfile% (
echo start logging... "%~0" on %date% %time% >> %logfile%
) ELSE (
echo Start Log for "%~0" on %date% %time% > %logfile%
)

Pinging Multiple PCs and Adding Text

I'm pretty new to this so please bear with me, and if you require anymore information from me please say. Thanks in advance for your help.
I have this code that pings different PCs then returns back if they are online/offline. I wanted to know if you could add another column once the bat file has ran its ping test so it has the computer name next to it.
#echo off
if exist C:\tools\computers.txt goto Label1
echo.
echo Cannot find C:\tools\computers.txt
echo.
Pause
goto :eof
:Label1
echo PingTest executed on %date% at %time% > C:\tools\z.txt
echo ================================================= >> C:\tools\z.txt
for /f %%i in (C:\tools\computers.txt) do call :Sub %%i notepad C:\tools\z.txt
goto :eof
:Sub
echo Testing %1 set state=alive ping -n 1 %1 | find /i "bytes=" || set state=dead echo %1 is %state% >> C:\tools\z.txt
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
99.1.82.28 is alive
99.1.82.100 is alive
ect.
If possible I would like the bat file to run so it displays this;
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
Computer 1 : 99.1.82.28 is alive
Computer 2 : 99.1.82.100 is alive
ect.
--
Would appreciate any help & guidance on this.
Thanks.
You can try this solution :
#echo off
Title Ping Test
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a : !ip! ALive ok" || set "msg=%%a : !ip! Dead failed to respond"
echo !msg!
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
EDIT : on 29/07/2016 # 12:48
Another version with multi-colors : Special thanks goes to ICARUS for the color function (-_°)
#echo off
Rem Special thanks goes to Iracus for the color function (-_°)
mode con cols=60 lines=20
Title Multi-Ping hosts Tester with Multi-colors by Hackoo
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
call :init
echo(
call :color 0E "------- Ping Status of Computers hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a - !ip! ALive ok" && Call :Color 0A "!msg!" 1 || set "msg=%%a - !ip! Dead failed to respond" && Call :Color 0C "!msg!" 1
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
EDIT : Update On 23/08/2016
http://pastebin.com/zjYwSqUM

Resources