net use in cmd script hangs forever – how to set a timeout if server denies connection

  abort, batch-file, cmd, timeout, windows

I have a Windows batch file which connects several network drives. It first pings the servers, and if that succeds, it then tries to map the share with net use ...:

SET host=mini3
IF /I NOT %host% == %COMPUTERNAME% (
    ping -4 -n 2 -w 1000 %host% | find "TTL=" > NUL
    IF !ERRORLEVEL! EQU 0 (
        echo Q: == %host%Q_ -- mini3-Volumes
        net use Q: %host%Q_ /persistent:yes > NUL && echo OK
    ) ELSE (
        echo %host% not found. Skipping.
    )
)

Sometimes, even though the machine is reachable by ping, the net use command hangs forever. The reason it hangs seems due to a misconfiguration in the SMB server, and/or in the Windows Credentials stored on the client.

So when that happens, for whatever reason, I would like to print an error and go on to the next drive to map.

The Windows Timeout command seems to actually be a "delay" command, equivalent of Unix sleep, and not a timeout.

Is there a good way to have a real timeout for a net use command, without aborting the entire .cmd script?

Source: Windows Questions

LEAVE A COMMENT