Vasu Deo.S
Vasu Deo.S

Reputation: 1850

batch file(.bat) showing unexpected behaviour

My batch Script:-

@echo off

:alpha

rasdial "connection_name" connection_id connection_pass> tmpFile 
set /p myvar= < tmpFile 
del tmpFile 
echo %myvar%
if "%myvar%" == "You are already connected to Broadband Connection." (exit)
goto alpha

This script is expected to run a command radial ... and then store the output of the command in a temprory file tempFile. Then it assigns the stored output of command radial inside this file to a variable, and deletes the file. The variable in turn is used to check whether the command got successfully executed or not (if command executed successfully then You are already connected to Broadband Connection. will be the output).

But upon executing this batch file I get output:-

Connecting to Broadband Connection...
The syntax of the command is incorrect.

and then the script breaks. Instead of looping through it again, until the command get's successfully executed.

OUTPUT AFTER ECHO ON:-

rasdial "Broadband Connection" uname pass  1>tmpFile

set /p myvar=   0<tmpFile

del tmpFile

echo You are already connected to Broadband Connection.
You are already connected to Broadband Connection.
The syntax of the command is incorrect.

if "You are already connected to Broadband Connection.
Command completed successfully." == "You are already connected to Broadband Connection." (exit)

Upvotes: 1

Views: 169

Answers (1)

Stephan
Stephan

Reputation: 56180

The variable myvar seems to contain a line feed (yes, that's really unexpected), ruining your if syntax.

You should switch to another method (suggested by @Marged)

:alpha
rasdial "Broadband Connection" uname pass  | find "You are already connected to Broadband Connection." && exit /b
timeout 1 >nul
goto :alpha

This pipes the ouptut of rasdial directly to the find command. && works as "If find is successful" (the string is found), then execute the exit command.

Tip: never build an infinite loop without some idle time (did it with timeout here) to prevent the CPU from running at 100%.

Upvotes: 3

Related Questions