3

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
aschipfl
  • 33,626
  • 12
  • 54
  • 99
Ebad Ali
  • 600
  • 1
  • 6
  • 29

2 Answers2

3

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
Compo
  • 36,585
  • 5
  • 27
  • 39
2

Your problem is a logical one: you check, if it's a folder, but you don't check, if it's a file, so you have either "folder" or "not a folder". You need another check for "file". But finding "Not Found" makes it language dependent, which generally should be avoided. Here is a language independent solution:

for does list all attibutes (there is a Direcotry attribute), which even attrib doesn't.

@echo off
break>Existing.File
md ExistingFolder

set "attr=Existing.File"
REM set "attr=ExistingFolder"
REM set "attr=does not exist"

for /f %%x in ("%attr%") do set attrib=%%~ax/
set "attrib=%attrib:~0,1%"
if "%attrib%"=="d" echo %attr% is a directory
if "%attrib%"=="-" echo %attr% is a file
if "%attrib%"=="/" echo %attr% does not exist

Note: this method even detects a folder, where you don't have access to (but does not detect such files)

Stephan
  • 53,940
  • 10
  • 58
  • 91