I've a controlfile.txt file in which I have some softwares names in each line, e.g. "Microsoft Office" in first line, then "Autodesk AutoCAD" in second line, "Adobe Acrobat Reader" in third line and so on. I need a batch script to fetch each line from that .txt file as a string (more than one word in a line) and google search each string (Software Name) in a separate tab for its license terms or EULA. I've this the following code, but it is not passing the value of array as a query for google search.

@echo off 
set "file=C:\New folder\controlfile.txt" 
set /A i=0 
for /F "usebackq delims=" %%a in ("%file%") do ( 
set /A i+=1 
call set array[%%i%%]=%%a 
call set n=%%i%% 
for /L %%i in (1,1,%n%) do ( 
call echo %%array[%%i]%% 
start "" chrome.exe www.google.com#q=%%array[%%i]%%+EULA 
  • Does it open anything in chrome? You've got something that converts spaces to +'s? – Xen2050 Mar 21 '18 at 5:39
  • @Xen2050 I have 4 line items in controlfile.txt, so when I run this batch script, Chrome opens 4 tabs and search for "%array[1]% EULA", "%array[2]% EULA", "%array[3]% EULA", "%array[4]% EULA" respectively in each tab. But I want that chrome searches for the value that is stored in "%array[1]% " and so on. – IamAD Mar 21 '18 at 6:13
  • You need to use Delayed Expansion. See enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time and also see my answer Windows CMD script to count files and get filenames which shows how to correctly simulate arrays in cmd. – DavidPostill Mar 21 '18 at 9:10

Why so complicated? I don't see any need to store the values in an array - you can simply launch each chrome tab directly within a single simple FOR /F loop.

@echo off
for /f "usebackq delims=" %%A in ("C:\New folder\controlfile.txt") do (
  echo %%~A
  start "" chrome.exe www.google.com#q="%%~A"+EULA

The reason why your array based code failed is because you forgot to use CALL with your START line.

call start "" chrome.exe www.google.com#q=%%array[%%i]%%+EULA

I much prefer using delayed expansion instead of the CALL trick, as delayed expansion is much faster.

@echo off
setlocal enableDelayedExpansion
set "file=C:\New folder\controlfile.txt"
set /a i=0
for /F "usebackq delims=" %%A in ("%file%") do (
  set /a i+=1
  set "array[!i!]=%%A"
for /L %%A in (1,1,%i%) do (
  echo !array[%%A]!
  start "" chrome.exe www.google.com#q=!array[%%A]!+EULA

Assuming none of your lines begin with :, you can do the first loop without CALL or DelayedExpansion

for /f "delims=: tokens=1*" %%A in ('findstr /n "^" "%file%"') do set "array[%%A]=%%B"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.