How to test if a path is a file or directory in Windows batch file?

前端 未结 6 580
心在旅途
心在旅途 2020-11-30 10:04

I searched here, found someone using this

set is_dir=0
for %%i in (\"%~1\") do if exist \"%%~si\"\\nul set is_dir=1

but didn\'t work, when

6条回答
  •  时光取名叫无心
    2020-11-30 10:52

    Previously, I used the "\nul" method, but for a long time now, I have used "\*" to test if an existing filespec is a folder or a file. As far as I know, it works on all versions of Windows, from Windows 95 (and perhaps earlier versions) through all current Windows versions.

    So, as with other methods, first test if the file exists. Then, to see if it's a "Folder", test it with: if exist "%fspec%\*":

    if not exist "%fspec%"   goto :NotExistOrInvalid
    
    rem "%fspec%" is "Valid" and is either a "Folder", or a "File".
    if     exist "%fspec%\*" goto :IsValidAndIsAFolder
    
    rem "%fspec%" is a "File" (a "Regular File" or a Shortcut/Link).
    goto :IsValidAndIsAFile
    

    For example:

    set "fspec=XYZ:%perlpath%"
    if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem Invalid, goto :NotExistOrInvalid
    
    set "fspec=%perlpath%"
    if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem goto :NotExistOrInvalid
    
    rem "%fspec%" Is a "Valid" filespec and is either a "Folder", or a "File".
    if exist "%fspec%\*" (echo "%fspec%" is a "Folder".) else echo "%fspec%" is a "File".
    
    set "fspec=%perlpath%\perl.exe"
    if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem Invalid, goto :NotExistOrInvalid
    
    rem "%fspec%" Is a "Valid" filespec and is either a "Folder", or a "File".
    if exist "%fspec%\*" (echo "%fspec%" is a "Folder".) else echo "%fspec%" is a "File".
    

    The output for this is:

    "XYZ:F:\usr\perl\bin": Invalid or not found
    "F:\usr\perl\bin" is a "Folder".
    "F:\usr\perl\bin\perl.exe" is a "File".
    

提交回复
热议问题