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.

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.