Looping a command in a Batch file - batch-file

cd \Users\Kurashima\AppData\Local\Android\sdk\platform-tools
adb devices
adb shell screenrecord /storage/ext_sd/vid001.mp4
adb shell screenrecord /storage/ext_sd/vid002.mp4
adb shell screenrecord /storage/ext_sd/vid003.mp4
Before getting to my question, I must first make a disclaimer. I am a beginner in writing batch files.
What I want to do is to make those last three lines into a loop that will execute any number of times, incrementing the number in the file name, until the Ctrl+C command is entered. I know how to make a simple loop, using :start and goto start, but I'd end up overwriting the same file every time. How do I avoid that?

Here is a complete script. Remove all REM to make it operational for you.
Note pause >NUL command waits for pressing any key (without prompting due to >NUL); after pressing Ctrl+C it will ask for Terminate batch job (Y/N)?.
Remove that pause >NUL line if you want to work unattended; the Ctrl+C functionality should retain; if does not retain, then use Ctrl+Break
#ECHO OFF >NUL
#SETLOCAL enableextensions disabledelayedexpansion
rem cd \Users\Kurashima\AppData\Local\Android\sdk\platform-tools
rem adb devices
set /A "ii=0"
:start
set /A "ii+=1"
set "ss=000%ii%"
set "ss=%ss:~-3%"
echo adb shell screenrecord /storage/ext_sd/vid%ss%.mp4
rem adb shell screenrecord /storage/ext_sd/vid%ss%.mp4
pause >NUL
if %ii% LSS 999 goto :start
:endlocal
#ENDLOCAL
goto :eof

Related

BATCH file reloading autorun buffer

There are things that we prefer not to understand in order to have an easier life to live.
But this is not something I can choose...
I made a batch file (or macro.doskey) to get the charset code. And it worked perfectly for a long time...
Basically it runs chcp:
> chcp
Code page active: 850
and then wraps the return before and after the colon
assigning what comes after to a variable:
FOR /F "tokens=1,* delims=:" %%s in ('CHCP') do (
#ECHO %%t
IF NOT "%1" == "" (SET %1=%%t)
)
For example:
> getCHCP.bat myVar
850
> ECHO %myVar%
850
However it started to lock, waiting for ENTER or displaying several echo messages. For example:
> getchcp myVar
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
ECHO is off.
850
I started to mix until I decided to change the ECHO %%t to ECHO %%s, and guess what?
No, is that the Bill Gates skull? Is it an easter egg from Microsoft? A virus?
No, none of that, this is just my autorun's welcome message.
This can be configured in
<[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]autorun>
In my case I called a batch file which, among other things, gives several echos showing this skull on the screen.
But the question is, why does it act like it reloads the autorun in background
when I've already opened the command prompt?
And why does it leave
everything in the buffer so that %%s pulls it again to the (Page code active) ':'?
And why are
you giving lots of ECHO is off on %%t when the only thing after
Code page active: is a number?
And the most important: How I solve it?
It's obvious, you already point to the problem.
this is just my autorun's welcome message.
This can be configured in
<[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]autorun>
The line FOR /F %%s in ('CHCP') ... start CHCP but that will be done in a NEW child cmd.exe instance.
And a NEW cmd.exe instance runs the autorun command!
Just before it starts your chcp.
You can disable the autorun at all, or add some code to detect the difference between a new cmd.exe instance for the user against a new instance from a FOR /F.
Put this code at the start of your autorun batch file
#echo off
setlocal EnableDelayedExpansion
REM *** ALWAYS make a copy of the complete CMDCMDLINE, else you destroy the originial!!!
set "_ccl_=!cmdcmdline!"
REM *** %1 contains only data, when the script itself was called from the command line
if "%~1" NEQ "" (
goto :direct_call
)
REM *** The check is necessary to distinguish between a new cmd.exe instance for a user or for a "FOR /F" sub-command
if "!_ccl_:~1,-2!" == "!comspec!" (
REM ***** INTERACTIVE ****
REM *** Show your skull or something else
)
exit /b

My Batch file loop stops because of open file

I am trying to build a batch file that pings multiple devices on our network and continues logging ping results data in an output file in an infinite loop. However, the infinite loop gets hung up because the output file is open. Once I manually close the output file, the loop begins another iteration and logs more data. How do I automate this step? I've gone through so many options with taskkill, but none of them will close the output file for some reason. Other Notepad files close, but not the output file running on notepad.
Thanks for you help! Code is below:
#echo off
if exist C:\Users\Tsgadmin\Desktop\data\computers.txt goto Label1
echo.
echo Cannot find C:\Users\Tsgadmin\Desktop\data\computers.txt
echo.
Pause
goto :eof
:Label1
:loop
echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo PingTest executed on %date% at %time% >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
for /f %%i in (C:\Users\Tsgadmin\Desktop\data\computers.txt) do call :Sub %%i
notepad C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
choice /n/t:c,<10>/c:cc
echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo. >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
start notepad.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr notepad.exe') do set PIDTOKILL=%%x
taskkill /F /IM notepad.exe > nul
goto loop
goto :eof
:Sub
echo Testing %1
ping -n 1 %1 >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt | find /i "(0% loss)"
echo %1 Testing done
echo %1 Testing done >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
Here is your batch code rewritten for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LogFile=%USERPROFILE%\Desktop\ping_firepanels_output.txt"
set "ListFile=%USERPROFILE%\Desktop\data\computers.txt"
if exist "%ListFile%" goto PrepareForPings
echo/
echo Cannot find file: "%ListFile%"
echo/
endlocal
pause
goto :EOF
rem Delete existing log file before running the echo requests.
rem Get just file name with file extension without path from
rem log file name with path specified at top of the batch file.
:PrepareForPings
del "%LogFile%" 2>nul
for /F %%I in ("%LogFile%") do set "LogFileName=%%~nxI"
rem Always terminate (not kill) running Notepad instance with having
rem the log file opened for viewing before running first/next test run.
:PingLoop
%SystemRoot%\System32\taskkill.exe /FI "WINDOWTITLE eq %LogFileName% - Notepad" >nul 2>nul
echo =================================================>>"%LogFile%"
>>"%LogFile%" echo PingTest executed on %DATE% at %TIME%
echo/>>"%LogFile%"
for /F "usebackq" %%I in ("%ListFile%") do (
echo Testing %%I ...
%SystemRoot%\System32\ping.exe -n 1 -w 500 %%I>nul
if errorlevel 1 (
echo %%I is not available in network (no reply^).>>"%LogFile%"
) else echo %%I is available.>>"%LogFile%"
echo %%I testing done.
)
echo =================================================>>"%LogFile%"
echo/>>"%LogFile%"
start "" %SystemRoot%\notepad.exe "%LogFile%"
echo/
%SystemRoot%\System32\choice.exe /C NY /N /T 10 /D Y /M "Run again (Y/n): "
echo/
if errorlevel 2 goto PingLoop
endlocal
In general it is advisable to define environment variables with names of files specified multiple times in the batch file at top to make it easier to modify them in future.
On referencing those file environment variables it is strongly recommended to enclose the name in double quotes to get a working batch file also when file name with path contains a space character or one of these characters: &()[]{}^=;!'+,`~
If a file name enclosed in double quotes is specified as text file of which lines to read in a for /F command line, it is necessary to use option usebackq to get interpreted the file name enclosed in double quotes as file name and not as string to process by FOR.
The DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ explains why it is better to use echo/ instead of echo. to output an empty line.
The TASKKILL command used to send Notepad the terminate signal for a graceful termination should be send only to the Notepad instance having the log file opened and not any other perhaps running Notepad instance.
An ECHO line redirected to a file with > or >> with a space left to redirection operator results in having this space also written as trailing space into the file. For that reason there should be no space between text to write into the file and redirection operator. A space right to > or >> would be no problem as not written into the file.
When a variable text is output on an ECHO line redirected into a file which could end with 1, 2, 3, ... 9, it is necessary to specify the redirection from STDOUT into the file with >> at beginning of the line as otherwise 1>>, 2>>, ... would be interpreted different as expected on execution of the ECHO command line. Read also the Microsoft article about Using Command Redirection Operators.
There is no subroutine necessary for this task. A command block starting with opening parenthesis ( and matching ) can be used here too. That makes the execution of the loop a bit faster, not really noticeable faster, but nevertheless faster.
There is a text written with echo into the log file containing also a closing parenthesis ) not within a double quoted string. This ) would be interpreted as matching ) for opening ( of true branch of IF condition. It is necessary to escape ) with caret character ^ to get ) interpreted as literal character by Windows command interpreter.
PING exits with exit code 1 if the echo request was not replied. Otherwise on successful reply the exit code is 0. It is better to evaluate the exit code via errorlevel than filtering the language dependent output.
New instance of Notepad with the log file to view is started by this batch file using command start to run Notepad in a separate process running parallel to command process executing the batch file. Otherwise the execution of the batch file would be halted as long as the started Notepad instance is not closed by the user. That different behavior can be easily seen on removing start "" at beginning of the command line starting Notepad.
The command CHOICE gives the user of the batch file the possibility to exit the loop by pressing key N (case-insensitive) within 10 seconds. Otherwise the user prompt is automatically answered with choice Y and the loop is executed once again by first terminating running Notepad.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
choice /?
del /?
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
ping /?
set /?
setlocal /?
start /?
taskkill /?
See also Windows Environment Variables for details on environment variables USERPROFILE and SystemRoot as used in this batch file.

Reading a Text File and Reacting (Batch)

I looked for quite a while and couldn't find a good solution to my problem. I want a batch program to "look" in a .txt file for the command "" and if that word is in it, then to execute a different command. If the command existed, I would want to do something like set %textfile%=text.txt and if that worked I would then do if %textfile%==update goto update which would be an easy way to start an automatic update if this was in a loop. So basically, is there a command that sets a text file in %text%? This is the code that I am trying to add this into:
#echo off
color 0f
:start
echo Welcome to Master control pannel
ping 127.1 -n 4 >nul
cls
:options
cls
echo What would you like to do first? (Type the number of the operation you want to start)
echo.
ping 127.1 -n 2 >nul
echo 1. Run a command off of all computers
::(I want to run a command by sending a message to a text file but want recieving computor to be able to read it and execute it, how could I read the command and then do what it say, for example, if the command says "echo Hello" I would want recieving computor to say "Hello" )
echo 2. Stops the current command
echo 3. List all computers
echo 4. Open remote shutdown program
echo 5. Delete a computor (in progress)
echo 6. (Unfinished)
echo 7. (Unfinished)
echo 8. (Unfinished)
echo 9. (Unfinished)
echo 10. Exit
set /p choose=(1-9):
if %choose%==1 goto o1
if %choose%==2 goto o2
if %choose%==3 goto o3
if %choose%==4 goto o4
if %choose%==5 goto o5
if %choose%==6 goto close
if %choose%==7 goto close
if %choose%==8 goto close
if %choose%==9 goto close
if %choose%==10 goto o10
goto options
:close
cls
goto start
:o1
echo Stopping current command
del command.txt
echo. 2>command.txt
echo Command stopped!
pause
cls
goto start
I would greatly appreciate some help or comments to what I could do or add to this. Thanks!
Not an answer but several hints.
a variable can hold only single lines not a whole file.
if you want to get the first line of a file into a var use `Set /P "var="
set %textfile%=text.txt would store test.txt literally into a var whose name is the content of the var textfile.
you are mixing goto o1 and :01 with the label
`

Batch script to move to another section of the script if there is no input from user

I am trying to get this script to jump to another section of the script if there is no input from the user.
Down at the if %input%== area.
What I'm trying to do is skip to the section where the script checks for .mp4 files and moves them if they are there. Am I supposed to set a variable or loop for that section? Thanks for any replies
#echo off
echo Checking for youtube-dl updates.
pause
youtube-dl -U
rem Enter the url or urls that you want to download from
set /p input="Enter the url(s) you want to download:"
rem Uses the youtube-dl continue (-c) option to download multiple files if not in a playlist
youtube-dl -c "%input%"
rem pause
if %input%=="" GOTO:EOF
cls
echo Download complete, please wait while files are transfered to appropiate folder
pause
for %%o in (.mp4) do move "*%%o" "E:\Documents\scripts\videos\"
if not exist do echo .mp4 files are no longer in this directory
pause
How about following script? This script waits for 3 seconds while "file.mp4" doesn't exist. It keeps to wait until the file exists. About "filename", you can change for your script.
#echo off
set waittime=3
set filename=file.mp4
:loop
if not exist %filename% (
Timeout /t %waittime% /nobreak > nul
goto loop
)
echo Find %filename%
When doing string comparison in batch you have to make sure, that both parts are equal, which in your case will never happen! In most languages strings have double quotes around them. In batch they usually do not.
To solve your problem enclose %input% in double quotes as well.
Note that it can be useful to do something like "x%input%"=="x" to prevent certain characters like <>|to be at the beginning of the comparison string.
You can check this on your own with these few lines:
#echo off
set /p input="Input something or nothing here "
echo %input%
echo "%input%"
pause
If you are hitting Return without any input you will see that only the bottom one will output "" which is the string you are comparing to.

bugfixer.bat batch file ask end user which option they want to run

fun stuff!!
Manager has just bought a humdinger of a utility. It does everything. It even has command line functionality. If you run BugFixer /a the application will automatically scan the entire drive for cooties. If you run the Bugfixer /b it will scan all of your files on the Windows\system 32 directory and if you run Bugfixer /c the program will scan and repair your Registry. Need to write a batch file that will allow your users to avoid that pesky GUI and efficiently run the Bug fixer through the command line, by asking them which option they would like to initialize.
:TOP
ECHO WHICH BUG FIXER DO YOU NEED TO RUN? A=ALL B=SOME c=REPAIR
SET /P = %USERSPEC%
IF "%1"=="A=ALL" GO TO :FIRST
IF "%1"=="A=all" GO TO :FIRST
:FIRST
CHKDSK C:
ECHO CHECKING ALL FILES ARE COMPLETE
IF "%2"=="B=SOME" GO TO :NEXT
IF "%2"=="b=some" GO TO :NEXT
:NEXT
CHKDSK /F /R C:\WINDOWS/SYSTEM32
ECHO CHECKING SOME FILES ARE COMPLETE
IF "%3"=="REPAIR" GO TO :LAST
IF "%3"=="repair" GO TO :LAST
:LAST
CHKDSK /c
ECHO REPAIR FILES ARE COMPLETED
Like I said fun stuff. Anyone wanna help?
Next script logic could become helpful:
#echo OFF >NUL
setlocal enableextensions
:TOP
echo(
set "USERSPEC="
set /P "USERSPEC=Which bug fixer do you need to run? A=all B=some C=repair? "
if /I "%USERSPEC%"=="A" goto :FIRST
if /I "%USERSPEC%"=="B" goto :NEXT
if /I "%USERSPEC%"=="C" goto :LAST
echo NO CHECK CHOOSEN, BATCH ENDS
goto :ENDSCRIPT
:FIRST
chkdsk C:
echo CHECKING ALL FILES ARE COMPLETE
goto :TOP
:NEXT
chkdsk /F /R C:\WINDOWS/SYSTEM32
echo CHECKING SOME FILES ARE COMPLETE
goto :TOP
:LAST
chkdsk /c
echo REPAIR FILES ARE COMPLETED
goto :TOP
:ENDSCRIPT
endlocal
goto :eof
However, running it:
==>30019117.bat
Which bug fixer do you need to run? A=all B=some C=repair? a
Access Denied as you do not have sufficient privileges.
You have to invoke this utility running in elevated mode.
CHECKING ALL FILES ARE COMPLETE
Which bug fixer do you need to run? A=all B=some C=repair?
NO CHECK CHOOSEN, BATCH ENDS
==>
Resources (advised reading):
An A-Z Index of the Windows CMD command line (command reference)
Windows CMD Shell Command Line Syntax (additional particularities)
Script resources for IT professionals (a huge Script repository)

Resources