My 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 result if a check with IF EXIST depend on whether
- the drive is a local drive or a mapped network drive or a UNC path
- the path contains spaces or not
- the path is quoted or not
- cmd runs in administrator mode or user mode
I wrote a small batch file that contains a couple of assignments of the form
set dir=c:\temp set dir=c:\temp\with spaces etc.
and executed these tests on each value
if exist %dir% echo exists if exist %dir%\nul echo exists if exist %dir%\. echo exists if exist "%dir%" echo exists if exist "%dir%\nul" echo exists if exist "%dir%\." echo exists
These are the results
|mapped (non-admin, spaces)||-||-||-||x||x|
Testing directory path containing spaces can only be performed using the quoted notation.
The only reliable way to test for directory existence is therefore to use the quoted “%dir%\.” notation.
To check whether cmd runs in administrator mode or not, use an admin statement such as ‘at’:
at >nul 2>nul if errorlevel 1 echo you are not in administrator mode