如何找出例如如果C:\Windows\something.tmp
是一个文件或目录?
有时应用程序将其临时数据写入具有扩展名的文件夹,删除目录与删除文件不同。 所以我必须为此调用一个不同的子程序。
下面的解决方案适用于普通和网络案例。 有很多混乱,甚至有关于区分文件和文件夹的激烈争论。 一个原因是从MS-DOS时代熟悉的方法(测试nul)不再是在Windows命令行中区分文件和文件夹的有效方法。 (这个变得越来越复杂了。)
@echo off & setlocal enableextensions if "%~1"=="" ( echo Usage: %~0 [FileOrFolderName] goto :EOF) :: :: Testing call :IsFolderFn "%~1" isfolder_ call :IsFileFn "%~1" isfile_ echo "%~f1" isfile_=%isfile_% isfolder_=%isfolder_% endlocal & goto :EOF :: :: Is it a folder :: First the potential case of the root requires special treatment :IsFolderFn setlocal if /i "%~d1"=="%~1" if exist "%~d1\" ( set return_=true& goto _ExitIsFolderFn) if /i "%~d1\"=="%~1" if exist "%~d1" ( set return_=true& goto _ExitIsFolderFn) set return_= dir /a:d "%~1" 2>&1|find "<DIR>">nul if %errorlevel% EQU 0 set return_=true :_ExitIsFolderFn endlocal & set "%2=%return_%" & goto :EOF :: :: Is it just a file :IsFileFn setlocal set return_= if not exist "%~1" goto _ExitIsFileFn call :IsFolderFn "%~1" isfold_ if defined isfold_ goto _ExitIsFileFn dir /a:-d "%~1" 2>&1 > nul if %errorlevel% EQU 0 set return_=true :_ExitIsFileFn endlocal & set "%2=%return_%" & goto :EOF
如何测试文件是批处理脚本中的目录?
简而言之 :
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
但是,所有的信用都去了Dave Webb
您可以使用dir /ad
告诉你
如果我检查errorlevel告诉我
用一个文件
C:\Users\preet>echo. > something.tmp C:\Users\preet>dir /ad something.tmp > nul & echo %errorlevel% 1 C:\Users\preet>del something.tmp
与一个目录
C:\Users\preet>md something.tmp C:\Users\preet>dir /ad something.tmp > nul & echo %errorlevel% File Not Found 0