How to Detect Network Cable Disconnections in Batch Script
A network outage isn't always a server failure; sometimes, it's a physical problem like a loose cable, a failing Wi-Fi card, or a disconnected Ethernet port. For a user, this looks like "Internet is Down," but for a system administrator, knowing the physical status of the network card is the key to a fast repair. A Batch script can query the "Media State" of your network adapters via WMIC or netsh, allowing you to trigger an alert the moment a "Cable Unplugged" event occurs.
This guide will explain how to monitor physical network connectivity.
Method 1: Using WMIC (Best for Physical Status)
The Win32_NetworkAdapter class provides a property called NetConnectionStatus:
- 0 = Disconnected
- 1 = Connecting
- 2 = Connected
- 7 = Media Disconnected (cable unplugged / no signal)
WMIC has been deprecated starting in Windows 11. See Method 4 for a forward-compatible PowerShell alternative.
@echo off
setlocal enabledelayedexpansion
set "AdapterName=Ethernet"
echo [MONITOR] Checking physical link status for "%AdapterName%"...
echo.
:: First, verify the adapter name exists on this system
set "found=0"
for /f "tokens=2 delims==" %%n in ('wmic nic get NetConnectionID /value 2^>nul') do (
for /f "delims=" %%m in ("%%n") do (
if /i "%%m"=="%AdapterName%" set "found=1"
)
)
if !found! equ 0 (
echo [ERROR] Adapter "%AdapterName%" not found on this system.
echo.
echo Available adapters:
echo -------------------
wmic nic where "NetConnectionID is not null" get NetConnectionID 2>nul
echo.
echo [TIP] Update the AdapterName variable to match one of the above.
pause
endlocal
exit /b 1
)
:: Query for the specific adapter status
:: Nested FOR strips the invisible \r that WMIC appends
set "status="
for /f "tokens=2 delims==" %%a in ('wmic nic where "NetConnectionID='%AdapterName%'" get NetConnectionStatus /value 2^>nul') do (
for /f "delims=" %%b in ("%%a") do set "status=%%b"
)
:: Validate we got a result
if not defined status (
echo [ERROR] Could not retrieve adapter status.
pause
endlocal
exit /b 1
)
:: Interpret the status code
if "!status!"=="2" (
echo [OK] Link is active and connected.
) else if "!status!"=="7" (
echo [ALERT] NETWORK CABLE IS DISCONNECTED!
) else if "!status!"=="0" (
echo [WARN] Adapter is disconnected (disabled or no cable^).
) else if "!status!"=="1" (
echo [INFO] Adapter is currently connecting...
) else (
echo [INFO] Adapter is in state: !status!
echo See NetConnectionStatus codes for details.
)
pause
endlocal
Why the nested FOR loop? WMIC's output appends invisible carriage return characters (\r) to every value. Without stripping them, the if comparisons silently fail: your script might report "unknown state" even when the adapter is perfectly connected.
Method 2: High-Speed "Media State" Check (Netsh)
netsh is very fast for checking the operational state of an interface without complex WMI parsing. It also works regardless of Windows language since we parse structured output.
@echo off
setlocal enabledelayedexpansion
echo [SCAN] Checking all network interface states...
echo.
echo INTERFACE STATE
echo ================================================
set "DisconnectedCount=0"
set "ConnectedCount=0"
:: Parse the netsh output - skip header lines, extract name and state
for /f "tokens=1,2,3,* delims= " %%a in ('netsh interface show interface 2^>nul ^| findstr /v /c:"---" ^| findstr /v /c:"Admin"') do (
set "adminState=%%a"
set "connState=%%b"
set "ifName=%%d"
if defined connState (
if /i "!connState!"=="Disconnected" (
echo [!!] !ifName! - DISCONNECTED
set /a DisconnectedCount+=1
) else if /i "!connState!"=="Connected" (
echo [OK] !ifName! -
Connected
set /a ConnectedCount+=1
)
)
)
echo ================================================
echo.
echo Connected: !ConnectedCount! Disconnected: !DisconnectedCount!
if !DisconnectedCount! gtr 0 (
echo.
echo [WARNING] One or more adapters are disconnected.
echo Check physical cables and Wi-Fi connections.
)
pause
endlocal
Method 3: The "Uptime Guard" Loop
Runs in the background to continuously monitor and log cable disconnection events with proper state tracking.
@echo off
setlocal enabledelayedexpansion
set "AdapterName=Ethernet"
set "LogFile=%USERPROFILE%\cable_monitor.log"
set "Interval=5"
set "WasDisconnected=0"
echo [GUARD] Monitoring link status for "%AdapterName%"...
echo Log: %LogFile%
echo Press CTRL+C to stop.
echo.
:Loop
set "status="
:: Check adapter status via WMIC
:: Nested FOR strips \r carriage returns
for /f "tokens=2 delims==" %%a in ('wmic nic where "NetConnectionID='%AdapterName%'" get NetConnectionStatus /value 2^>nul') do (
for /f "delims=" %%b in ("%%a") do set "status=%%b"
)
:: Handle cable disconnected (status 7) or adapter disconnected (status 0)
if "!status!"=="7" (
if !WasDisconnected! equ 0 (
echo [!date! !time!] CABLE DISCONNECTED on %AdapterName% >> "%LogFile%"
echo [!time!] [ALERT] CABLE PULLED on %AdapterName%!
set "WasDisconnected=1"
)
) else if "!status!"=="0" (
if !WasDisconnected! equ 0 (
echo [!date! !time!] ADAPTER DISCONNECTED on %AdapterName% >> "%LogFile%"
echo [!time!] [ALERT] Adapter disconnected on %AdapterName%!
set "WasDisconnected=1"
)
) else if "!status!"=="2" (
if !WasDisconnected! equ 1 (
echo [!date! !time!] RECONNECTED on %AdapterName% >> "%LogFile%"
echo [!time!] [OK] Connection restored on %AdapterName%.
set "WasDisconnected=0"
)
)
timeout /t %Interval% >nul
goto :Loop
Method 4: Using PowerShell (Modern / Windows 11 Compatible)
Since WMIC is deprecated, this is the recommended approach for current and future Windows versions. It also provides richer adapter information.
@echo off
setlocal
echo [SCAN] Checking physical link status (PowerShell^)...
echo.
powershell -NoProfile -Command "$adapters = Get-NetAdapter -ErrorAction SilentlyContinue; if (-not $adapters) { Write-Host '[ERROR] No network adapters found.'; exit 1 }; Write-Host (' {0,-30} {1,-15} {2}' -f 'ADAPTER','STATUS','LINK SPEED'); Write-Host (' ' + '-' * 60); $disconnected = 0; foreach ($a in $adapters) { $icon = if ($a.Status -eq 'Up') { '[OK]' } else { '[!!]' }; $speed = if ($a.LinkSpeed) { $a.LinkSpeed } else { 'N/A' }; Write-Host (' {0} {1,-30} {2,-15} {3}' -f $icon, $a.Name, $a.Status, $speed); if ($a.Status -ne 'Up') { $disconnected++ } }; Write-Host (' ' + '-' * 60); if ($disconnected -gt 0) { Write-Host ''; Write-Host (' [WARNING] ' + $disconnected + ' adapter(s) are not connected.') } else { Write-Host ''; Write-Host ' [OK] All adapters are connected.' }"
pause
endlocal
How to Avoid Common Errors
Wrong Way: Using "Ping" to Check the Cable
If you ping and fail, you don't know why. It could be the server is down, the router is off, or your DNS is broken.
Correct Way: Use WMIC, netsh, or Get-NetAdapter. These check the hardware level. If your script reports "Status 7," it means the network card literally cannot detect an electrical signal from the other end of the wire, a definitive physical diagnosis.
Wrong Way: Hardcoding "Ethernet" as the Adapter Name
The adapter name varies between machines: "Ethernet," "Ethernet 2," "Local Area Connection," "Wi-Fi," or vendor-specific names like "Intel(R) I219-V."
Correct Way: List available adapter names first, then use the correct one:
:: WMIC method
wmic nic where "NetConnectionID is not null" get NetConnectionID
:: PowerShell method
powershell -NoProfile -Command "Get-NetAdapter | Select-Object Name, Status"
Wrong Way: Using WMIC Output Without Stripping \r
WMIC appends invisible carriage return characters to every value. String comparisons like if "%status%"=="2" silently fail because the variable actually contains 2\r.
Correct Way: Use a nested FOR /F to strip the trailing characters:
for /f "tokens=2 delims==" %%a in ('wmic ... /value') do (
for /f "delims=" %%b in ("%%a") do set "var=%%b"
)
Problem: Adapter Names on Different Machines
If you deploy a script across multiple computers, the adapter named "Ethernet" on your machine might be called "Ethernet 2" or "Local Area Connection" on another.
Solution: Method 1 includes adapter validation that lists available names if the specified one isn't found. For enterprise deployment, consider querying by adapter type rather than name, or use Method 4's Get-NetAdapter which can filter by media type.
Best Practices and Rules
1. Distinguish Wi-Fi vs. Ethernet
A "Media Disconnected" state on Wi-Fi usually means you are out of range or have the wrong password. On Ethernet, it almost always means a physical hardware issue (loose cable, bad port, failed switch).
2. Administrator Privileges
Querying hardware status via WMIC generally requires running the script as an Administrator to get accurate results across all system adapters. netsh interface show interface and PowerShell's Get-NetAdapter typically work without elevation.
3. Log the Event
When a cable is disconnected, log the timestamp and the specific adapter name so you can track if a specific desk or port has a recurring "bad cable" problem:
echo [%date% %time%] DISCONNECTED - %AdapterName% >> cable_events.log
4. WMIC Deprecation
Microsoft has deprecated WMIC starting in Windows 11. For forward-compatible scripts, use PowerShell's Get-NetAdapter (Method 4) or Get-CimInstance Win32_NetworkAdapter.
5. State Tracking for Continuous Monitoring
When running a monitoring loop, always track state transitions (connected → disconnected, disconnected → connected) rather than logging every poll. This keeps log files compact and makes outage duration easy to calculate.
6. Always Use setlocal / endlocal
Without setlocal, every variable your script creates persists in the parent shell session, causing potential conflicts when running multiple scripts in sequence.
Conclusions
Detecting physical network cable disconnections moves your troubleshooting from "Layer 3" (software) down to "Layer 1" (hardware). By identifying a "Media Disconnected" state instantly, you bypass hours of unnecessary software debugging and go straight to the root cause. This professional hardware-level visibility ensures that you can maintain a robust, physically sound network infrastructure and respond to connectivity crises with confidence.