batch file (windows cmd.exe) test if a directory is a link (symlink) batch file (windows cmd.exe) test if a directory is a link (symlink) windows windows

batch file (windows cmd.exe) test if a directory is a link (symlink)


You have three methods

Solution 1: fsutil reparsepoint

Use symlink/junction with fsutil reparsepoint query and check %errorlevel% for success, like this:

set tmpfile=%TEMP%\%RANDOM%.tmpfsutil reparsepoint query "%DIR%" >"%tmpfile%"if %errorlevel% == 0 echo This is a symlink/junctionif %errorlevel% == 1 echo This is a directory

This works, because fsutil reparsepoint query can't do anything on a standard directory and throws an error. But the permission error causes %errorlevel%=1 too!

Solution 2: dir + find

List links of the parent directory with dir, filter the output with find and check %errorlevel% for success, like this:

set tmpfile=%TEMP%\%RANDOM%.tmpdir /AL /B "%PARENT_DIR%" | find "%NAME%" >"%tmpfile%"if %errorlevel% == 0 echo This is a symlink/junctionif %errorlevel% == 1 echo This is a directory

Solution 3: for (the best)

Get attributes of the directory with for and check the last from it, because this indicates links. I think this is smarter and the best solution.

for %i in ("%DIR%") do set attribs=%~aiif "%attribs:~-1%" == "l" echo This is a symlink/junction

FYI: This solution is not dependent on %errorlevel%, so you can check "valid errors" too!

Sources


general code:

fsutil reparsepoint query "folder name" | find "Symbolic Link" >nul && echo symbolic link found || echo No symbolic link

figure out, if the current folder is a symlink:

fsutil reparsepoint query "." | find "Symbolic Link" >nul && echo symbolic link found || echo No symbolic link

figure out, if the parent folder is a symlink:

fsutil reparsepoint query ".." | find "Symbolic Link" >nul && echo symbolic link found || echo No symbolic link


Actually, DIR works fine if you append an asterisk to the filename, thus:

dir %filename%* |  find "<SYMLINKD>" && (   do stuff)

GreenAsJade called my attention to this solution's failure when there is another entry in the directory that matches %filename%*. I believe the following wiull work in all cases:

set MYPATH=D:\testdir1set FILENAME=mylinkset FULL=%MYPATH%\%FILENAME%set SP1=0for /f "tokens=4,5 delims= " %%A IN ('dir /L /N %FULL%*') do (    if %%B EQU %FILENAME% (    if "%%A" EQU "<SYMLINKD>" set SP1=1    ))if %sp1% EQU 0 echo It's not there.if %sp1% EQU 1 echo BINGO!Pause