How to test if a path is a file or directory in Windows batch file?

I know the if exist path\nul test for a folder used to work on MS-DOS. I don’t know if it was broken with the introduction of long file names.

I knew that if exist "long path\nul" does not work on Windows batch. I did not realize until today that if exist path\nul works on Vista and beyond as long as path is in the short 8.3 form.

The original code appears to work on Vista. It seems like it should work on XP as well, but I believe the following XP bug is getting in the way: Batch parameter %~s1 gives incorrect 8.3 short name.

The original code does not need the FOR loop, it could simply use %~s1

Here is a variation that fully classifies a path as INVALID, FILE or FOLDER. It works on Vista, but does NOT work on XP because of the %~s1 bug. I’m not sure how it performs on MS-DOS.
EDIT 2015-12-08: There are a number of Windows situations where this fails

@echo off
if not exist "%~1" ( set "type=INVALID" ) else if exist %~s1\nul ( set "type=FOLDER" ) else ( set "type=FILE" )
@echo "%~1" = %type%

I believe this variation will work with nearly all versions of Microsoft batch, including MS-DOS and XP. (it obviously won’t work on early versions of DOS that don’t support PUSHD)

@echo off
if exist "%~1" (2>nul pushd "%~1" && (popd&set "type=FOLDER") || set "type=FILE" ) else set "type=INVALID"
echo "%~1" = %type%

UPDATE 2014-12-26

I’m pretty sure the following will work on all versions of Windows from XP onward, but I have only tested on Win 7.
Edit 2015-12-08: This can fail on network drives because the folder test can falsely report a file as a folder

@echo off
if exist %1\ (
  echo %1 is a folder
) else if exist %1 (
  echo %1 is a file
) else (
  echo %1 does not exist
)

UPDATE 2015-12-08

Finally – a test that truly should work on any Windows version from XP onward, including with network drives and UNC paths

for /f "tokens=1,2 delims=d" %%A in ("-%~a1") do if "%%B" neq "" (
  echo %1 is a folder
) else if "%%A" neq "-" (
  echo %1 is a file
) else (
  echo %1 does not exist
)

Note – This technique is intended to be used for a path without any wildcards (a single specific file or folder). If the provided path includes one or more wildcards, then it provides the result for the first file or folder that the file system encounters. Identical directory structures may give different sort order results depending on the underlying file system (FAT32, NTFS, etc.)

Leave a Comment