因工作需要,需要判断参数传递过来的路径是文件夹还是文件,于是从网上找来一些,供大家参考吧
版本1
@echo off if exist "C:\1" (dir /ad/b "C:\1" 2>nul&&set a=0||set a=1) echo %a% pause
版本2
for %%a in (C:\1) do set "b=%%~aa" if defined b ( if %b:~0,1%==d (set a=1 ) else ( set a=0) ) 说明:得到C:\1的属性,然后判断属性首字节是否为d,是为文件夹,否为文件,如果变量a没被赋值,则没有这个文件(夹)
版本3
@echo off cd C:\1 2>nul if %ERRORLEVEL% ==1 (set a=1) else (set a=0) echo %a% pause
版本4
@echo off if exist c:\1 if exist c:\1\nul echo c:\1 is a folder. if exist c:\1 if not exist c:\1\nul echo c:\1 is a file.
出处:https://zhidao.baidu.com/question/303954579943369244.html
=======================================================================================
版本5
REM 判断要复制的是文件还是目录 FOR %%i IN ("%FileName%") DO SET FileAttrib=%%~ai IF %FileAttrib:~0,1%==d ( GOTO COPYDIR ) ELSE ( GOTO COPYFILE )
版本6
@echo off for /f "delims=" %%i in ('dir /a/b/s') do pushd "%%i" 2>nul && (call :folder "%%i" & popd) || call :file "%%i" pause goto :eof :file echo %~1 是文件 goto :eof :folder echo %~1 是目录 goto :eof
pushd %%i 2>nul && (echo 目录 & popd )|| echo 文件
或者:
pushd %%i 2>nul
if %errorlevel% == 1 (echo 文件
)else(echo 目录)
大概就是这样吧,具体的语法不大记得了,不知道上面的能不能正常执行。
另外可以通过dir /ad/b/s来获得所有目录,dir /a-d/b/s来获得所有非目录。
个人认为在dir里面区别对待文件和目录是提高效率的做法。
出处:https://bbs.csdn.net/topics/360126535
=======================================================================================
版本7
set arg=c:\ttt if exist "%arg%\.\" echo yes
出处:https://tieba.baidu.com/p/1204278138
=======================================================================================
使用批处理检查路径是“文件"还是“文件夹"(Check if the path is File or Folder using batch)
我正在尝试使用批处理文件检查程序中定义的路径是文件还是文件夹.一切正常,但是当我尝试提供的路径不是文件或文件夹或没有访问权限时,它会显示"这是一个文件".
这是代码.
@ECHO off SETLOCAL ENABLEEXTENSIONS set ATTR=D:\Download\Documents\New dir /AD "%ATTR%" 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir) :IsFile echo %ATTR% is a file goto done :IsDir echo %ATTR% is a directory goto done :done解决方案
我建议使用以下方法:
@Echo Off Set "ATTR=D:\Download\Documents\New" For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" (Echo Directory ) Else If "%%~aZ" GEq "-" (Echo File) Else Echo Inaccessible Pause
I am trying to check if the path defined in the program is file or a folder using batch file. Everything is working fine but when I try to give a path that isn't file or folder or doesn't have permission to access it, it gives output saying "it is a File".
Here is the code.
@ECHO off SETLOCAL ENABLEEXTENSIONS set ATTR=D:\Download\Documents\New dir /AD "%ATTR%" 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir) :IsFile echo %ATTR% is a file goto done :IsDir echo %ATTR% is a directory goto done :done解决方案
I would suggest the following method:
@Echo Off Set "ATTR=D:\Download\Documents\New" For %%Z In ("%ATTR%") Do If "%%~aZ" GEq "d" (Echo Directory ) Else If "%%~aZ" GEq "-" (Echo File) Else Echo Inaccessible Pause
出处:https://www.it1352.com/1966715.html
=======================================================================================
我推荐使用版本7,比较简单,其他的各个版本,大家自行选择吧