0

How to find out for example if C:\Windows\something.tmp is a file or a directory?

Sometimes applications write their temporary data to a folder with an extension, and deleting a directory differs from deleting a file. So I must call a different subroutine for that.

Mofi
  • 46,139
  • 17
  • 80
  • 143
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • 2
    possible duplicate of [How do I test if a file is a directory in a Batch script?](http://stackoverflow.com/questions/138981/how-do-i-test-if-a-file-is-a-directory-in-a-batch-script) – Helen Nov 28 '11 at 11:00

3 Answers3

1

The solution below works both for ordinary and network cases. There is much confusion and has even been heated arguments about distinguishing between files and folders. One reason is that the method familiar from the MS-DOS days (testing for the nul) is no more the valid solution to distinguish between a file and a folder in the Windows command-line. (This is getting complicated.)

@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

Originally from http://www.netikka.net/tsneti/info/tscmd075.htm

Timo Salmi
  • 254
  • 3
  • 3
1

How to test if a file is a directory in a batch script?

In short :

FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory

But all credits go to Dave Webb

Community
  • 1
  • 1
Alex Garcia
  • 773
  • 7
  • 21
1

You can used dir /a-d to tell you

if I check errorlevel it tells me

With a file

C:\Users\preet>echo. > something.tmp

C:\Users\preet>dir /a-d something.tmp > nul & echo %errorlevel%
1

C:\Users\preet>del something.tmp

with a directory

C:\Users\preet>md something.tmp

C:\Users\preet>dir /a-d something.tmp > nul & echo %errorlevel%
File Not Found
0
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216