Search code examples
batch-fileseleniumfor-loopsubroutine

Second instance of batch loop does not run


I am trying to create a DOS batch script on my Windows 7 machine. I want to execute file 123456.bat, which contains the following command and parameters:

call **startSelenium.bat** 55 someSuiteName suite-someSuite.html development 1 1 10 10

That script calls into the startSelenium.bat script below:

Setlocal EnableDelayedExpansion

SET TimeStamp= 
FOR /f "tokens=1-4 delims=/ " %%i in ("%date%") do set datestr=%%l%%j%%k
FOR /f "tokens=1-4 delims=.: " %%i in ("%time%") do set timestr=%%i%%j%%k%%l
SET TimeStamp=%datestr%%timestr%

set a=2
set b=0
set /a c=%a%+%b%

FOR /l %%t IN (1, 1, %c%) do (
  call :SEARCHPORT %%t
  echo %startPort%
  Start java -jar C:\Selenium\2\selenium-server-standalone-2.47.1.jar -port %startPort% -singleWindow -userExtensions C:\selenium\2\user-extensions.js -firefoxProfileTemplate "c:\selenium\2\ffprofiles\2rc" -htmlSuite "*chrome" "https://www.google.com" "Z:\selenium\2\environment\%4\suites\%3" "u:\results\%4\result-%1-%computername%-1234-%TimeStamp%.htm"  
  timeout /t 10
)
GOTO :EOF

:SEARCHPORT 

netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
  set /a startPort +=1
  GOTO :SEARCHPORT
) ELSE (
  set freePort=%startPort%
  echo %startPort%

GOTO :EOF

When I run the script, the first instance of the java applications runs with a free Windows port that the SEARCHPORT subroutine found; however, the second instance pops up and quits immediately. I suspect the code is using the same variable from the first time it went through the FOR loop instead of getting a new unused port number.

What am I doing wrong? I copied various parts of this code from other sources. I am obviously a nube, so plain English would be helpful. :)


Solution

  • You have got an delayed expansion issue.

    You already enabled delayed expansion, but you don't use it. You have to replace %startPort% with !startPort! inside your for /l loop.