title: How can I reliably validate existence of a directory via WinXP batch script?
body: <p>Howdy, I'm writing a <strong>batch script</strong> that will run on a <strong>Windows XP</strong> machine. This script needs to be able to reliably validate that a directory, passed as a command-line parameter, does in fact exist.</p>
  
  <p>Assuming my script is named <strong>script.bat</strong>, it needs to support the following as legal command-line parameters:</p>
  
  <pre><code>C:\&gt; script.bat C:
  C:\&gt; script.bat C:\
  C:\&gt; script.bat ..\photos
  C:\&gt; script.bat C:\WINDOWS
  C:\&gt; script.bat "C:\Documents and Settings"
  C:\&gt; script.bat "C:\Documents and Settings\"
  C:\&gt; script.bat F:\music\data\
  C:\&gt; ...
  </code></pre>
  
  <p>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 <em>MUST</em> 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:</p>
  
  <pre><code>C:\&gt; script.bat "F:\music\data\"
  </code></pre>
  
  <p>My first attempt looks like this:</p>
  
  <pre><code>@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!
  </code></pre>
  
  <p>The <em>main</em> problem is that it doesn't work when a path with embedded spaces is specified:</p>
  
  <pre><code>C:\script.bat "C:\Documents and Settings"
  ...
  'and' is not recognized as an internal or external command,
  operable program or batch file.
  </code></pre>
  
  <p>So, I tried quoting the %dir% variable as follows:</p>
  
  <pre><code>IF NOT EXIST "%dir%" GOTO :BadDirectory
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Any help or comments will be <em>greatly</em> appreciated!</p>
  
  <p>--
  Signed: wish I were writing bash shell scripts, ruby, or anything else instead...</p>