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

前端 未结 6 599
心在旅途
心在旅途 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 11:04

    This solution combines the file attribute parameter extension (%~a1) with variable substring extraction (%variable:~0,1%):

    @ECHO OFF
    
    CALL :is_directory C:\Windows
    CALL :is_directory C:\MinGW\share\doc\mingw-get\README
    CALL :is_directory C:\$Recycle.Bin
    CALL :is_directory "C:\Documents and Settings"
    CALL :is_directory "%LOGONSERVER%\C$\Users\All Users"
    
    GOTO :EOF
    
    :is_directory
        SETLOCAL
        SET file_attribute=%~a1
        IF "%file_attribute:~0,1%"=="d" (
            ECHO %file_attribute% %1 is a directory
        ) ELSE (
            ECHO %file_attribute% %1 is NOT a directory
        )
        ENDLOCAL
        GOTO :EOF
    

    Output:

    d-------- C:\Windows is a directory
    --a------ C:\MinGW\share\doc\mingw-get\README is NOT a directory
    d--hs---- C:\$Recycle.Bin is a directory
    d--hs---l "C:\Documents and Settings" is a directory
    d--hs---l "\\MYCOMPUTER\C$\Users\All Users" is a directory
    

提交回复
热议问题