Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop working in CMD prompt but not in batch file - for loop was copy pasted

Note: I have almost no idea at all how batch file 'for' loops work.

The batch file I have currently:

"C:\Program Files (x86)\HMA! Pro VPN\bin\HMA! Pro VPN.exe" -connect
"C:\Program Files (x86)\HMA! Pro VPN\bin\HMA! Pro VPN.exe" -changeip  
ping -w 2000 -n 1 1.1.1.1
:wait
for /f "usebackq tokens=1,2,3,*" %A in (`netsh interface show interface`) do @if "%D"=="Local Area Connection 2" set state=%B
if %state%==Connected goto :end
goto :wait
:end

I'm trying to write a robust IP changer that utilizes HMA! Pro VPN - it should work whether the VPN client has been opened or not, and whether the VPN is currently opened or not, and should pause until the VPN has connected.

If you Google the for loop, you'll see it appear in a stackoverflow answer - this for loop works perfectly fine in a CMD prompt, and sets %state% to Connected/Disconnected well, but in a batch file, throws the following error:

D"=="Local was unexpected at this time.

I would learn more about for loops in batch had I not been under a very tight schedule - I have learnt about these before, but this loop looks pretty weird to me.

like image 476
Shariq Avatar asked Jun 28 '12 16:06

Shariq


People also ask

How does for loop work in batch?

For loop (default) of Batch language is used to iterate over a list of files. Example: copy some files into a directory (Note: the files to be copied into the target directory need to be in the same disk drive).

How do I run a loop in cmd?

FOR /D - Loop through several folders. FOR /L - Loop through a range of numbers. FOR /F - Loop through items in a text file. FOR /F - Loop through the output of a command.


1 Answers

In a batch file you have to use two percents for FOR parameters, that's all

for /f "usebackq tokens=1,2,3,*" %%A in (`netsh interface show interface`) do (
    if "%%D"=="Local Area Connection 2" set state=%%B
)
like image 143
jeb Avatar answered Sep 21 '22 14:09

jeb