- 1 year ago
net use in cmd script hangs forever - how to set a timeout if server denies connection
If the net use
command in a CMD script hangs indefinitely when the server denies the connection, you can set a timeout value using the timeout
command or by checking the errorlevel value returned by net use
. Here's how you can implement it:
Using the
timeout
command:batch@echo off
set server=\\ServerName\ShareName
set timeout_seconds=10
net use %server% /user:username password
rem Check the errorlevel value
if %errorlevel% neq 0 (
echo Connection to %server% failed.
timeout /t %timeout_seconds%
rem Handle timeout scenario
) else (
rem Connection successful
rem Continue with the script
)
In this example, the
timeout
command is used to introduce a delay oftimeout_seconds
(set to 10 seconds in this case) after thenet use
command. If thenet use
command fails and returns a non-zero errorlevel, it indicates a failed connection. The script then proceeds to the timeout section, where you can handle the timeout scenario as needed.Checking the errorlevel value directly:
batch@echo off
set server=\\ServerName\ShareName
set timeout_seconds=10
net use %server% /user:username password
rem Check the errorlevel value
if %errorlevel% neq 0 (
echo Connection to %server% failed.
rem Introduce a loop to wait for the specified timeout
setlocal enabledelayedexpansion
set timeout_end_time=!time!
set /a timeout_end_time=!timeout_end_time:~0,2! * 3600 + !timeout_end_time:~3,2! * 60 + !timeout_end_time:~6,2! + %timeout_seconds%
:loop
timeout /t 1 /nobreak >nul
net use %server% >nul 2>&1
if not %errorlevel% equ 0 (
rem Connection failed within the timeout period
echo Connection to %server% failed.
exit /b
)
setlocal enabledelayedexpansion
set current_time=!time!
set /a current_time=!current_time:~0,2! * 3600 + !current_time:~3,2! * 60 + !current_time:~6,2!
if !current_time! lss !timeout_end_time! goto :loop
rem Connection successful within the timeout period
rem Continue with the script
)
In this approach, after the
net use
command, a loop is introduced that checks the errorlevel of subsequentnet use
commands until the timeout period is reached or the connection is successful. The script calculates the end time of the timeout and repeatedly checks the connection status until the timeout period expires or a successful connection is made. You can customize the timeout behavior and handle the timeout scenario accordingly.
Choose the method that suits your requirements and adjust the timeout duration to fit your specific needs.