I am trying to make a batch file to quickly ping a number of devices to make sure they are all still on the network. If I type the commands in by hand, it seems give the expected output once, but doesn't seem to loop through the other iterations. Putting them in a batch file and running it somehow messes with my ability to call a variable. The IP just comes up as "i"
Is there something I'm missing? Thanks for the help.
set Device[0].Name=PC1
Set Device[0].IP=192.168.1.1
set Device[1].Name=PC2
Set Device[1].IP=192.168.1.2
set Device[2].Name=PC3
Set Device[2].IP=192.168.1.3
set _filepath=%userprofile%
echo %date% %time% > %_filepath%
SET /A i=0
:loop
IF %i%==3 GOTO END
call ping -n 1 %IDF[%i%].IP% | find "TTL=" >nul
if errorlevel 1 (
call echo %IDF[%i%].Name% IS OFFLINE >> %_filepath%
) else (
call echo %IDF[%i%].Name% Online >> %_filepath%
)
SET /A i=%i%+1
GOTO :loop
:END
In place of set /a i=0 onwards,
for /L %%s in (0,1,2) do (
CALL ping -n 1 %%Device[%%s].IP%% | find "TTL=" >nul
if errorlevel 1 (
CALL echo %%Device[%%s].Name%% IS OFFLINE >> %_filepath%
) else (
CALL echo %%Device[%%s].Name%% Online >> %_filepath%
)
)
The for /L (start,step,end) command can then be easily altered to process an extended list without using a goto
Noting that I severely suspect your setting of _filepath since it appears to be assigned a directoryname, not a filename
Also, use set "var1=data" for setting values - this avoids problems caused by trailing spaces. In comparisons, use if "thing1" == "thing2" ... to avoid problems caused by spaces in thing1/2.
I am facing a problem with my following batch script, where I can see how the execution of the command %nr% --f !path2! never seems to happen and I don't understand the reason.
What am I doing wrong? Too many nested conditions ?
EDIT: adding WRONG code where comments are enabled
rem The call to this batch script will be this
rem C:/Projects/DevelopmentTools/SDKs/TP/B/Scrpt/Exg_Serial_Flasher.bat EF.hex DH.hex C:/Projects/DevelopmentTools/SDKs/TP/B/E/Output/CN/Exe/
setlocal enabledelayedexpansion
set nr=nr.exe
if "%1"=="" (
if "%2"=="" (
if "%3"=="" (
echo "[Error]"
set "runScript="
)
)
) else (
set "input1=%1"
set "input2=%2"
set "path3=%3%nr%"
set "myPath"=%3"
set "path1=!myPath!!input1!"
set "path2=!myPath!!input2!"
rem Control variable
set "runScript=true"
)
if defined runScript (
if exist "%path3%" (
%nr% --check
if exist !path1! (
%nr% --f !input1!
echo !ERRORLEVEL!
if !ERRORLEVEL! EQU 0 (
echo !input1! set correctly
if exist !path2! (
echo Setting !exgSerial!
%nr% --f !input2!
if !ERRORLEVEL! EQU 0 (
echo Everything went fine
)
)
)
)
)
)
Thanks!
I suggest following batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ExeFile=nr.exe"
if "%~1" == "" goto ArgumentError
if "%~2" == "" goto ArgumentError
if not "%~3" == "" goto ProcessArguments
:ArgumentError
echo Error: %~nx0 must be called with three arguments.
exit /B 1
:ProcessArguments
rem Assign third argument to an environment variable.
set "FilePath=%~3"
rem Replace forward slashes by backslashes which is the directory separator on Windows.
set "FilePath=%FilePath:/=\%"
rem Make sure the file path ends with a backslash.
if not "%FilePath:~-1%" == "\" set "FilePath=%FilePath%\"
set "HexFile1=%FilePath%%~1"
set "HexFile2=%FilePath%%~2"
set "ExeFile=%FilePath%%ExeFile%"
if not exist "%ExeFile%" echo Error: "%ExeFile%" does not exist. & exit /B 2
if not exist "%HexFile1%" echo Error: "%HexFile1%" does not exist. & exit /B 3
if not exist "%HexFile2%" echo Error: "%HexFile2%" does not exist. & exit /B 3
"%ExeFile%" --check
"%ExeFile%" --f "%HexFile1%"
if errorlevel 1 echo Error: Processing "%HexFile1%" failed. & exit /B 4
"%ExeFile%" --f "%HexFile2%"
if errorlevel 1 echo Error: Processing "%HexFile2%" failed. & exit /B 4
echo Everything worked fine.
endlocal
An error condition is detected as soon as possible with resulting in exiting batch file processing with an appropriate error message and exit code.
There is no need for delayed environment variable expansion which makes processing the batch file faster and avoids problems with directory or file names containing an exclamation mark.
Name of a file or the file path can contain also command line critical characters like space or one of these characters &()[]{}^=;!'+,`~.
There are no nested IF conditions making successful execution flow straight from top to bottom.
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.
call /? ... explains %~1 which expands to argument 1 with removing any surrounding quotes.
echo /?
endlocal /? ... used here implicit on exiting batch file processing with exit and explicit at end of batch file.
exit /?
goto /?
if /?
rem /?
setlocal /?
See also Single line with multiple commands using Windows batch file.
I think I found the issue, it has to do with the fact that the "echos" to debug seem to influence the script execution. So in the code of my question, if I enable the echos, the script will fail running whereas if I disable them( commented out as below), the script does work.
Nevertheless, I don't understand why it does fail with the echos in first instance.
Code with disabled echos and working
rem The call to this batch script will be this
rem C:/Projects/DevelopmentTools/SDKs/TP/B/Scrpt/Exg_Serial_Flasher.bat EF.hex DH.hex C:/Projects/DevelopmentTools/SDKs/TP/B/E/Output/CN/Exe/
setlocal enabledelayedexpansion
set nr=nr.exe
if "%1"=="" (
if "%2"=="" (
if "%3"=="" (
echo "[Error]"
set "runScript="
)
)
) else (
set "input1=%1"
set "input2=%2"
set "path3=%3%nr%"
set "myPath"=%3"
set "path1=!myPath!!input1!"
set "path2=!myPath!!input2!"
rem Control variable
set "runScript=true"
)
if defined runScript (
if exist "%path3%" (
%nr% --check
if exist !path1! (
%nr% --f !input1!
rem echo !ERRORLEVEL!
if !ERRORLEVEL! EQU 0 (
rem echo !input1! set correctly
if exist !path2! (
rem echo Setting !exgSerial!
%nr% --f !input2!
if !ERRORLEVEL! EQU 0 (
echo Everything went fine
)
)
)
)
)
)
AIMS:
Learn how to use empty variables in a FOR LOOP routine in a batch file.
PROBLEM:
I am using whether a variable is defined or not to determine the appropriate subroutine in my script; 2 variables defined == go do something. One is defined but not the other == do something else. Both not defined == something else again.
The script checks for C$ access and the presence of a certain file within the C$ of a text file list of networked PC's. If both criteria are met by 2 variables having data set, a simple xcopy updates the file in question by going to a certain subroutine and then the LOOP moves to the next PC on the network to try and do the same.
If there is an issue I want to use the variables in an empty state to then do something else; for example report to text file that c$ was not accessible or the file was missing meaning bad install etc.
However on my 2 test machines I am breaking the folder paths to trip the error reporting routines and finding something strange I can't fix without writing more lines of code. In my text file I have 2 PC's listed a few times e.g.
PC1
PC2
PC1
PC2
PC1
PC2
PC1 has a broken file path to test error logging
PC2 All fine to test file update process
When I run the script PC1 gets reported as having a problem and logs correctly.
PC2 all is fine and the update happens fine. BUT THEN it hits PC1 again, but seems to think [even though file path still broken] that it is OKAY --as if the variable is remembered from the previous loop and of course tries to update and has problems.
Here is the code I was trying to get to work using empty variable
#echo off
color 0E
pushd %~dp0
setlocal EnableDelayedExpansion
for /f "usebackq tokens=*" %%i in ("%~dp0hostnames.txt") do (
rem Test Access Admin Shares C$
if exist "\\%%i\C$\Windows\System32" set dollar=yes
rem Test Installation Integrity
if exist "\\%%i\C$\ProgramData\config.cfg" set install=ok
echo %%i
echo !dollar!
echo !install!
pause
IF !dollar!==yes IF !install!==ok (call :updatecfg %%i)
IF !dollar!==yes IF [!install!]==[] (call :installerror %%i)
IF [!dollar!]==[] (call :errorshare %%i)
)
echo THE END
pause
exit
:updatecfg
CLS
XCOPY "%~dp0config.cfg" /Y "\\%1\C$\ProgramData" & echo %1 Update Config.cfg Succeeded! & echo %1 Update Succeeded! >>"%~dp0logpass.txt"
ping 127.0.0.1 -n 3 >nul
goto :eof
:errorshare
CLS
echo.
echo %1 Has C$ Access Issues [Logging] & echo %1 Has C$ Access Issues >>"%~dp0logfail.txt"
ping 127.0.0.1 -n 3 >nul
goto :eof
:installerror
CLS
echo.
echo %1 Cannot Find Config.cfg^!^! [Logging] & echo %1 Cannot Find Config.cfg^!^! Not Installed or Configured^? >>"%~dp0logfail.txt"
ping 127.0.0.1 -n 4 >nul
goto :eof
If I add if not exist entried to the 2 at the start and have them set something when there is a problem then this works fine. But I'd like to know if this the right way to do this or should I also be able to use empty variables. I am nearly there it's just that they are not clearing properly per loop.
Many thanks.
....
for /f "usebackq delims=" %%i in ("%~dp0hostnames.txt") do (
rem Clear variables for each iteration
set "dollar="
set "install="
rem Test Access Admin Shares C$
if exist "\\%%i\C$\Windows\System32" set "dollar=yes"
rem Test Installation Integrity
if exist "\\%%i\C$\ProgramData\config.cfg" set "install=ok"
if defined dollar (
if defined install (
call :updatecfg %%i
) else (
call :installerror %%i
)
) else (
call :errorshare %%i
)
)
....
or
....
for /f "usebackq delims=" %%i in ("%~dp0hostnames.txt") do (
rem Test Access Admin Shares C$
if exist "\\%%i\C$\Windows\System32" ( set "dollar=yes" ) else ( set "dollar=" )
rem Test Installation Integrity
if exist "\\%%i\C$\ProgramData\config.cfg" ( set "install=ok" ) else ( set "install=" )
if defined dollar (
if defined install (
call :updatecfg %%i
) else (
call :installerror %%i
)
) else (
call :errorshare %%i
)
)
....
In any case, you should ensure the variables have the adecuated value before taking a decision based on their content.
I'm trying to write a script to check if the remote workstations have 64bit or 32bit operating system. The script simple should check if the directory "Program Files (x86)" exists and then echo the results to the output.txt file. For some reason or another the script doesn't even create the output.txt file. Any suggestions?
#echo off
SET output=D:\output.txt
IF EXIST "%output%" DEL "%output%"
FOR /f %%a IN (computers.txt) DO (
CALL :ping %%a
)
GOTO :EOF
:ping
SET pingtest=false
ping -n 1 %1 | find "approximate round trip time" >NUL || SET pingtest=true
set directorytest=true
set directory="\\%1%\c$\Program Files (x86)\"
IF pingtest==true (
dir %directory% >nul 2>nul
if errorlevel 1 (
set directorytest=false
)
IF directorytest==true ( echo "%1;64bit" >> "%output%" ) ELSE ( ECHO "%1;32bit" >> "%output%" )
)
IF pingtest==false (
ECHO "%1;offline" >> "%output%"
)
:EOF
There are a couple of things wrong with your code.
When assigning your %directory% variable you use \\%1%\c$\Program Files (x86). Here %1% should be %1
You are using the c$ share, which is mostly not available anymore (or at least not without administative privilidges)
It could work like this:
#echo off
setlocal enabledelayedexpansion
echo Welcome
call :ping 192.168.1.1
echo.
echo done with everything
goto eof
:ping
echo Probing %1 ...
set pingtest=false
ping -n 1 %1 | find "Approximate round trip" > nul
IF %ERRORLEVEL% == 0 (
set tdir="\\%1\c$\Program Files (x86)"
echo Looking up !tdir!
dir !tdir!
if !ERRORLEVEL! == 0 (
set arch=64bit
) else (
set arch=32bit
)
echo Architecutre of %1 is: !arch! >> output.txt
) else (
echo Remote host unreachable: %1 >> output.exe
)
goto eof
BUT:
This will return 64bit for every machine that runs the microsoft sharing service or samba and that does not share C$ to just anyone, as dir will only return a non zero ERRORLEVEL when the target does not provide that service or generally is unavailable.
On the other hand every machine that does not provide the shareing service at all, will be marked as 32bit
For any machine that does provide access to it's root drive (which none should) the script does work.
Here is a more reliably method of checking for 32/64 bit Windows OS
#echo off
set RemoteHost=192.168.1.100
set RegQry=HKLM\Hardware\Description\System\CentralProcessor\0
reg \\%RemoteHost%\%RegQry% > checkOS.txt
find /i "x86" < CheckOS.txt > StringCheck.txt
IF %ERRORLEVEL% == 0 (
echo "This is 32 Bit Operating system"
) ELSE (
echo "This is 64 Bit Operating System"
)
[source]
This one utilizes the reg.exe that can query the registry of remote Windows NT machines.
There is also the possiblity of utilizing wmic: Example
IF pingtest==true (
will never be true because the string pingtest and true are not the same.
You need
IF %pingtest%==true (
Even when you've fixed that, there's a further gotcha:
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.
Search for 'delayed expansion' on SO for many, many, many examples.
I am writing a batch script that will loop through each line of a text file, (each line containing a filename) check if the file exists and then runs the file and moves it.
Here is my batch script:
REM Loop through each line of input.txt
FOR /F "tokens=1-3 delims=, " %%i IN (./ready/input.txt) DO (
ECHO.
ECHO.
ECHO.
ECHO Check %%i exists, set error flag if it doesnt
if not exist .\ready\%%i set errorlevel=2
echo return code is %errorlevel%
ECHO Run %%i if it exists
if errorlevel 0 call .\ready\%%i
ECHO Move %%i to archive if no error occured
if errorlevel 0 copy .\ready\%%i .\archive\%mydate%_%mytime%_%%j_%%k_%%i
ECHO Copy line of text to the new output.txt file if an error occured
if %errorlevel% NEQ 0 >>output.txt %%i, %%j, %%k
)
Here is the output:
I do not understand why the "if errorlevel" is not working as expected... if the file does not exist (as in this example where it does not exist) it should NOT try to run the file, it should NOT copy the file, and it should echo a 2 not a 0
Edit 1: I was reading another SO Post regarding "delayed environment variable expansion" I am not sure if this issue is related
ERRORLEVEL and %ERRORLEVEL% are two different variables. That means your code with echo return code is %errorlevel% and if %errorlevel% NEQ 0 >>output.txt %%i, %%j, %%k is probably wrong.
ERRORLEVEL is builtin and used to fetch the result of the last command. You can use it like:
IF ERRORLEVEL 1 ECHO error level is 1 or more
ERRORLEVEL cannot be set, just like bash does not let you set ?= ...
%ERRORLEVEL% is an environmental variable. If %ERRORLEVEL% is set, then its used in your script when you use %ERRORLEVEL%. If %ERRORLEVEL% is not set AND if command extensions are enabled, then it falls back to ERRORLEVEL. ERRORLEVEL does not update %ERRORLEVEL%.
Raymond Chen has a good blog entry on it: ERRORLEVEL is not %ERRORLEVEL%. Some of the content in this answer was shamelessly lifted from it.
#ECHO OFF
SETLOCAL
DEL output.txt 2>nul
REM Loop through each line of input.txt
FOR /F "tokens=1-3 delims=, " %%i IN (.\ready\input.txt) DO (
ECHO.
ECHO.
ECHO.
ECHO Check %%i exists, set error flag if it doesnt
if exist .\ready\%%i (set "errorflag=") ELSE (set errorflag=2)
CALL echo return code is %%errorflag%%
ECHO Run %%i if it exists
if NOT DEFINED errorflag (
call .\ready\%%i
ECHO Move %%i to archive if no error occured
if errorlevel 1 (SET errorflag=3) ELSE (ECHO copy .\ready\%%i .\archive\%mydate%_%mytime%_%%j_%%k_%%i)
)
ECHO Copy line of text to the new output.txt file if an error occured
if DEFINED errorflag >>output.txt ECHO %%i, %%j, %%k
)
GOTO :EOF
Here's a rewritten procedure.
Note: output.txt is deleted at the start, else the >> would append to any existing file. 2>nul suppresses error messages if the delete fails (eg. file not exist)
Within a block statement (a parenthesised series of statements), the ENTIRE block is parsed and THEN executed. Any %var% within the block will be replaced by that variable's value AT THE TIME THE BLOCK IS PARSED - before the block is executed.
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the chnaged value of var or 2) to call a subroutine to perform further processing using the changed values.
Note therefore the use of CALL ECHO %%var%% which displays the changed value of var. CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.
IF DEFINED var is true if var is CURRENTLY defined.
ERRORLEVEL is a special varable name. It is set by the system, but if set by the user, the user-assigned value overrides the system value.
IF ERRORLEVEL n is TRUE if errorlevel is n OR GREATER THAN n. IF ERRORLEVEL 0 is therefore always true.
The syntax SET "var=value" (where value may be empty) is used to ensure that any stray spaces at the end of a line are NOT included in the value assigned.
The required commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO COPY to COPY to actually copy the files.
I used the following input.txt:
seterr1.bat, J1, K1
seterr5.bat,J2,K2
seterr0.bat,J3 K3
seterr5.bat, J4, K4
notexist.bat, J5, K5
With existing files seterr*.bat which contain
#ECHO OFF
EXIT /b 1
(where the 1 in the last line determines the errorlevel returned)
and received the resultant output:
Check seterr1.bat exists, set error flag if it doesnt
return code is
Run seterr1.bat if it exists
Move seterr1.bat to archive if no error occured
Copy line of text to the new output.txt file if an error occured
Check seterr5.bat exists, set error flag if it doesnt
return code is
Run seterr5.bat if it exists
Move seterr5.bat to archive if no error occured
Copy line of text to the new output.txt file if an error occured
Check seterr0.bat exists, set error flag if it doesnt
return code is
Run seterr0.bat if it exists
Move seterr0.bat to archive if no error occured
copy .\ready\seterr0.bat .\archive\__J3_K3_seterr0.bat
Copy line of text to the new output.txt file if an error occured
Check seterr5.bat exists, set error flag if it doesnt
return code is
Run seterr5.bat if it exists
Move seterr5.bat to archive if no error occured
Copy line of text to the new output.txt file if an error occured
Check notexist.bat exists, set error flag if it doesnt
return code is 2
Run notexist.bat if it exists
Copy line of text to the new output.txt file if an error occured
Note that the COPY is merely ECHOed as I mentioned earlier.
and output.txt
seterr1.bat, J1, K1
seterr5.bat, J2, K2
seterr5.bat, J4, K4
notexist.bat, J5, K5
Use something like the following subroutine:
:return
ECHO #exit /b %1 >ret.cmd
CALL ret.cmd
GOTO :eof
Then use it like this:
:Attempt
SETLOCAL
CALL somethingThatFails
SET retcode=!errorlevel!
CALL somethingThatPasses : don't care about the errorlevel here
CALL :return !retcode!
ENDLOCAL
CALL :eof
So, the whole thing would looke something like:
test.cmd...
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
CALL :Attempt
IF !errorlevel! NEQ 0 (ECHO Attempt Failed) ELSE (ECHO Attempt succeeded!)
GOTO :eof
:Attempt
SETLOCAL
CALL somethingThatFails
SET retcode=!errorlevel!
CALL somethingThatPasses : don't care about the errorlevel here
CALL :return %retcode%
ENDLOCAL
CALL :eof
:return
ECHO #exit /b %1 >return.cmd
CALL ret.bat
GOTO :eof
somethingthatfails.cmd...
DIR some command that fails >nul 2>&1
somethingthatpasses.cmd...
DIR >nul 2>&1
The one side effect of this is a file laying around called ret.cmd. I usually use an :end subroutine that does cleanup and would delete it.
There is an easy way to set the %errorlevel% with a trick I learned several years ago:
:: force errorlevel to 1
#(call)
echo %errorlevel%
:: force errorlevel to 0
#(call )
echo %errorlevel%
pause
The space after call is necessary to set the %errorlevel% to 0.
Update: After researching this, I found a reference here.
For posterity, when specifically setting it to 0, I like
ver >nul
ver.exe always returns 0.
This is designed to execute the %%i item only if it exists and follow through with checking for errors and move or log. if the %%i item doesn't exist then it will do nothing.
REM Loop through each line of input.txt
FOR /F "tokens=1-3 delims=, " %%i IN (.\ready\input.txt) DO (
ECHO.
ECHO.
ECHO.
ECHO Check %%i exists, execute it if it does
if exist .\ready\%%i (
call .\ready\%%i
ECHO Move %%i to archive if no error occured
if not errorlevel 1 (
copy .\ready\%%i .\archive\%mydate%_%mytime%_%%j_%%k_%%i
) else (
ECHO Copy line of text to the new output.txt file if an error occurred
>>output.txt %%i, %%j, %%k
)
)
)
for me, simple use of cmd /c exit 2 worked to set the errorlevel and use it locally in a batch file and even after it ended to ask for the errorlevel outside:
set errorlevel=2
:
cmd /c exit %errorlevel%
:
if errorlevel 3 echo 3
if errorlevel 2 echo 2
if errorlevel 1 echo 1
if errorlevel 1 echo 0
Results
>test.bat
2
1
0
>if errorlevel 2 echo 2
2