Search code examples
windowsbatch-filenetwork-programmingcommand-linewifi

How to Loop Wifi connect command while disconnected, until connected, in a batch file?


I read up on For loops but im not sure how to integrate an IF statement to make it look more like a WHILE statement.

Windows Task scheduler will pick up disconnect events and run my batch file.

While wifi disconnected from "GUHOA" SSID run the "netsh wlan connect name=GUHOA" command every 5 seconds until its connected then stop.

Any ideas?

This is what im building off of:

netsh interface show interface | find "Enabled        Connected      Dedicated        Wireless Network Connection" /I /C
IF %ERRORLEVEL% equ 1 (
  netsh wlan connect name=GUHOA | echo Connecting to GUHOA 
) ELSE (
  echo Already connected 
)

Solution

  • a for might not be the best solution here. Use a simple loop instead:

    :loop
      netsh interface show interface | find "Enabled        Connected      Dedicated        Wireless Network Connection" /I /C
      IF %ERRORLEVEL% equ 0 goto :connected
      netsh wlan connect name=GUHOA | echo Connecting to GUHOA 
      timeout 5 >nul
    goto :loop
    
    :connected
    echo I'm connected.
    

    note: with netsh ... | echo something you pipe the output of netsh to echo, so you won't see it (but maybe that's your intention)