Howdy, I'm writing a batch script that will run on a Windows XP machine. This script needs to be able to reliably validate that a directory, passed as a command-line parameter, does in fact exist.
Assuming my script is named script.bat, it needs to support the following as legal command-line parameters:
C:\> script.bat C:
C:\> script.bat C:\
C:\> script.bat ..\photos
C:\> script.bat C:\WINDOWS
C:\> script.bat "C:\Documents and Settings"
C:\> script.bat "C:\Documents and Settings\"
C:\> script.bat F:\music\data\
C:\> ...
Basically, it must be legal to give a drive letter, with or without a trailing backslash as well as the full, absolute or relative path name, with or without a trailing backslash (and with or without spaces in some of the directory name(s)). The name MUST be quoted, obviously, if it contains spaces so as to be interpreted as one parameter. However, quotes should be allowed on names where they're not otherwise required:
C:\> script.bat "F:\music\data\"
My first attempt looks like this:
@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
IF ErrorLevel 1 GOTO :NoExtensions
IF "%~1"=="" GOTO :NoDirectory
SET dir=%~1\NUL
ECHO You provided: %1
ECHO Testing using: %dir%
IF NOT EXIST %dir% GOTO :BadDirectory
SET dir=%~f1\
ECHO The following is valid: %dir%
REM
REM Other script stuff here...
REM
GOTO :EOF
:NoExtensions
ECHO This batch script requires extensions!
GOTO :EOF
:NoDirectory
ECHO You must provide a directory to validate!
GOTO :EOF
:BadDirectory
ECHO The directory you specified is invalid!
The main problem is that it doesn't work when a path with embedded spaces is specified:
C:\script.bat "C:\Documents and Settings"
...
'and' is not recognized as an internal or external command,
operable program or batch file.
So, I tried quoting the %dir% variable as follows:
IF NOT EXIST "%dir%" GOTO :BadDirectory
Quoting as above seems to work when using "IF NOT EXIST" to check for files directly, but it doesn't work at all when using the "dir\NUL" trick to check for directories.
Another glitch in the original version is that if %1 is C: then the %~f1 version of the variable always seems to yield my current working directory instead of C: or C:\ as would be more useful. I'm not really sure of the best way to work around this either.
Any help or comments will be greatly appreciated!
-- Signed: wish I were writing bash shell scripts, ruby, or anything else instead...