How to check internet connection in .cmd (batch script) and run another command based on whether WiFi is connected or not?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To check the internet connection in a batch script (.cmd), you can use the ping command to ping a reliable host, such as Google's DNS server (8.8.8.8), and check if the ping is successful. Here's an example of how you can achieve this:

batch
@echo off

ping 8.8.8.8 -n 1 >nul
if %errorlevel% equ 0 (
echo Internet connection is available.
REM Run your command here when connected to the internet
) else (
echo Internet connection is not available.
REM Run your command here when not connected to the internet
)

In the above example, the ping command is used with the -n 1 parameter to send a single ping request. The >nul redirection is used to suppress the output. The %errorlevel% variable is checked to determine if the ping was successful. If the %errorlevel% is 0, it means the ping was successful, indicating an internet connection is available. You can replace the echo statements with your desired commands or actions.

By placing your desired commands inside the appropriate if and else blocks, you can run different commands based on whether the WiFi is connected or not.