How can I reliably verify the existence of a directory through a WinXP script package?

Howdy, I am writing a script package that will run on a Windows XP machine . This script should reliably verify that the directory passed as a command line parameter really exists.

Assuming my script is named script.bat , it should support the following command line options:

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 should be legal to give a drive letter with or without a backslash, as well as the full, absolute, or relative path name with or without a backslash (and with spaces in any directory or without name (s)) . The name MUST be indicated, obviously, if it contains spaces in order to be interpreted as a single parameter. However, quotes should be allowed by name, where they are not 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 does not work when the 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 to refer to the% dir% variable as follows:

IF NOT EXIST "%dir%" GOTO :BadDirectory

The quote, as mentioned above, works when using "IF NOT EXIST" to check files directly, but when using the "dir \ NUL" trick to check directories, it does not work at all.

, % 1 - C: % ~ f1 , , C: C: \, . , .

!

- : bash shell-, ruby ​​ - ...

+3
2

. IF EXIST , PUSHD. , IF EXIST , 90% 50% . . , - , , . , "dir\nul", . , , System Volume Information. .

CD PUSHD , , .

(: , , SVN).

@echo off
setlocal enableextensions
rem this one works reliably
if "%~1"=="" goto NoDirectory

pushd %1 2>nul && popd || goto :BadDirectory

echo DOES EXIST

endlocal
goto :eof

:NoDirectory
echo NO DIR
exit /b 1

:BadDirectory
echo DOES NOT EXIST
exit /b 1

, :

SUMMARY
   Succeeded: 60
   Failed:    0
   -----------------
   Total:     60

, : , . -, , .

: setlocal , , script DOS Windows 9x/ME. , .cmd .bat. AMissico , . .cmd , DOS, WinDOS . , : -)

, , , VBScript . Windows script Windows 98 ( Win 7 :-)), .

+8

\*, \NUL, . c: "%~1\*" (Windows c:\\* c:\folder\\*)

, , "% ~ [flags] 1", , % ! _ ^ (space)

+4

Source: https://habr.com/ru/post/1717487/


All Articles