Reputation: 1477
I use batch script to connect network drives on laptop, as standard way (via drive mapping) tries to connect them before WIFI gets connected, therefore is not always successful. This script used to work for almost last 3 years without any problems.
@echo off
net use * /del /yes
net use /persistent:no
:Loop
for /L %%A in (1,1,50) do (
ping DiskStation | find /i "bytes=" && goto Connected
ping LocalHost -n 3 > nul
ECHO %%A
)
rundll32 user32.dll,MessageBeep -1
goto Finish
:Connected
ping LocalHost -n 3 > nul
net use X: \\DiskStation\NaszePhotoVideo
net use Z: \\DiskStation\NaszeDane
:Finish
Script has stopped to work after Windows 10 April 2018 Update. Seems it cannot exit loop at ping DiskStation | find /i "bytes=" && goto Connected
.
When I ping DiskStation in other command line window all works fine with standard result from the command.
Upvotes: 0
Views: 316
Reputation: 49167
A for
loop can be exited in general with command goto
, but not a for /L
loop. This not expected behavior can be seen on Windows XP or any later Windows by running a batch file from within a command prompt window with just this command line:
@for /L %%A in (1,1,5) do if %%A == 3 @echo EQUAL & goto :EOF
The output is:
if 1 == 3
if 2 == 3
if 3 == 3
EQUAL
if 4 == 3
if 5 == 3
The command goto :EOF
has no effect on execution. The loop is run nevertheless five times although on third iteration the if
condition is true and echo
outputs EQUAL
, but goto
is not executed by Windows command processor.
A solution is not using for /L
in this case.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LoopCount=0"
set "SysPath=%SystemRoot%\System32"
%SysPath%\net.exe use * /del /yes >nul
:Loop
%SysPath%\ping.exe -n 1 DiskStation | %SysPath%\find.exe /I "bytes=" >nul 2>&1 && goto Connected
%SysPath%\ping.exe 127.0.0.1 -n 3 >nul
set /A LoopCount+=1
echo %LoopCount%
if not %LoopCount% == 50 goto Loop
%SysPath%\rundll32.exe user32.dll,MessageBeep -1
goto Finish
:Connected
%SysPath%\ping.exe 127.0.0.1 -n 3 >nul
%SysPath%\net.exe use X: \\DiskStation\NaszePhotoVideo /persistent:no
%SysPath%\net.exe use Z: \\DiskStation\NaszeDane /persistent:no
:Finish
endlocal
A loop coded with a jump label, an environment variable counted up using an arithmetic expression, a string comparison condition and a jump to the label is slower than for /L
, but that does not matter here on this task.
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.
echo /?
endlocal /?
find /?
for /?
goto /?
net /?
net use /?
ping /?
set /?
setlocal /?
Upvotes: 1