Test if Network Directory exists in Batch file (.cmd)

The default way to check whether a directory exists in a Windows batch file (.cmd) is

if not exist "%directory%\nul" (
echo %directory% does not exist
)

However, as this MS KB explains, the check for the NUL file does not work with directories on network drives mapped to a drive letter.

A working solution I found is to process the ERRORLEVEL value a DIR command sets

dir %directory% >nul 2>nul
if errorlevel 1 (
echo %directory does not exist
)

or

dir %directory% >nul 2>nul
if not errorlevel 1 (
echo %directory exists
)

Also note that mapped network drives are not available in administrator mode, as is discussed in these threads.

2 Responses to Test if Network Directory exists in Batch file (.cmd)

1. […] previous post on testing network drives led me to further research the topic, and I came to quite surprising (at least for me) results: the […]

2. […] Most interestingly, this year’s posts that got the most hits up to today are related to batch programming, which is not really one of my core areas: Test if Directory exists in Batch file (.cmd) and Test if Network Directory exists in Batch file (.cmd) […]