How-to: Check if a path is a file or a directory

Check if a given path leads to a folder or a file:

isdir.cmd

@Echo off
Setlocal
Set _path=%1
Set _attr=%~a1

:: Check the path exists
if not exist %_path% Echo Error not found &(CALL)&goto:eof

:: Reject any path ending in .. e.g. C:\..
if "%_path:~2%" EQU ".." (Echo %1 is invalid &(CALL)&goto:eof)

:: Test attribute to see if a file or folder
if "%_attr:~0,1%" NEQ "d" (Echo %1 is a file. &(CALL)) Else (
Echo %1 is a folder.)

The (CALL) command in the script will raise the errorlevel to 1 if no folder is found. You could also use Exit /b.

Adapted from this StackOverflow answer.

Examples

Test a directory:

C:\> isdir.cmd "C:\example\some folder"
"C:\example\some folder" is a directory

Test a directory and read the Errorlevel:

C:\> isdir C:\demo
C:\> If %errorlevel% EQU 1 Echo Demo folder not found

“The time you enjoy wasting is not wasted time” ~ Bertrand Russell

Related commands

How-to: Parameters - Command Line Arguments %1 %~f1
ATTRIB - Extended Attributes.
IF command (IF EXISTS).
How To: Find out if a directory is empty.
PowerShell: Get-ChildItem -directory


 
© BACK 2 Rank aka Tracer
"Lameness is not a reason for suicide but posing with eliteness is a reason for murders"