Related
I learned just now that this is a way to test in a batch file if a file is a link:
dir %filename% | find "<SYMLINK>" && (
do stuff
)
How can I do a similar trick for testing if a directory is a symlink. It doesn't work to just replace <SYMLINK> with <SYMLINKD>, because dir %directoryname% lists the contents of the directory, not the directory itself.
It seems like I need some way to ask dir to tell me about the directory in the way that it would if I asked in the parent directory. (Like ls -d does in unix).
Or any other way of testing if a directory is a symlink?
Thanks!
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%.tmp
fsutil reparsepoint query "%DIR%" >"%tmpfile%"
if %errorlevel% == 0 echo This is a symlink/junction
if %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%.tmp
dir /AL /B "%PARENT_DIR%" | find "%NAME%" >"%tmpfile%"
if %errorlevel% == 0 echo This is a symlink/junction
if %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=%~ai
if "%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
http://blogs.technet.com/b/filecab/archive/2013/02/14/dfsr-reparse-point-support-or-avoiding-schr-246-dinger-s-file.aspx
How to get attributes of a file using batch file
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
Update: this solved my problem, but as commenters noted, dir will show both directory symlinks and directory junctions. So it's wrong answer if junctions are there.
Simple dir /A:ld works fine
dir /?:
DIR [drive:][path][filename] [/A[[:]attributes]] …
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
Note that to execute a command only for non-link folders, you can use the attribute negation form:
for /F "usebackq" %%D in (`dir /A:D-L /B some-folder`) do (
some-command some-folder\%%D
)
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:\testdir1
set FILENAME=mylink
set FULL=%MYPATH%\%FILENAME%
set SP1=0
for /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
This also works:
dir /al|find /i "java"|find /i "junction" && (
echo directory is a symlink
)
The appropriate DIR command is shown in the following batch file (reparse.bat) -
:: Specify the Directory to search
SET directory=C:\Users\%username%\Desktop\TEST1
:: Results Text
echo SEARCH OF DIRECTORY FOR REPARSE POINTS & echo.
:: List files with ATTRIBUTE L (Reparse Points)
DIR "%directory%" /A:L
echo. && echo Notes - && echo.
echo There are 3 types of Reparse points: && echo.
echo ^<JUNCTION^> is a Directory Junction
echo ^<SYMLINKD^> is a Directory SymLink
echo ^<SYMLINK^> is a File SymLink
echo. && echo.
An alternative approach is to treat each of the three types of reparse point separately, in the following batch file (reparse2.bat), which can be easily modified to search only for the type of link you are interested in -
:: Directory to Search
SET directory=C:\Users\%username%\Desktop\TEST1
:: Results Text
echo SEARCH OF DIRECTORY: %directory% & echo.
:: Find FILE SymLinks in directory
dir "%directory%" | find "<SYMLINK>" && (
echo This is a SymLink FILE
) && ( echo. )
:: Find DIRECTORY SymLinks in directory
dir "%directory%" | find "<SYMLINKD>" && (
echo This is a SymLink DIRECTORY
) && ( echo. )
:: Find JUNCTIONS in directory
dir "%directory%" | find "<JUNCTION>" && (
echo This is a Directory JUNCTION
) && ( echo. ) && ( echo. )
A simple example script for Windows 10.
Info: If it exist as SymLink in %localappdata%\MegaDownloader folder, execute MegaDownloader.exe. If it doesn't exist as a SymLink in %localappdata%\MegaDownloader, use mklink to create SymLink PortableData path of current folder to %localappdata%\MegaDownloader, then runs MegaDownloader.exe.
fsutil reparsepoint query "%localappdata%\MegaDownloader" | find "Substitute" >nul && GOTO MD || mklink /D /J "%localappdata%\MegaDownloader" "%cd%\PortableData" >nul 2>&1
:MD
"%~dp0\MegaDownloader.exe"
OR
For symbolic and/or directory check, this commands is more robust:
set CheckFolder=D:\ExampleFolder
FOR /f "delims=<> tokens=2" %g in ('dir %CheckFolder%* ^| find "<"')
do ( IF %g==DIR (echo %CheckFolder% is real a directory.) ELSE (IF
%g==JUNCTION (echo %CheckFolder% is a SymbolicLink/Junction.) ) )
FOR /F "tokens=3*" %s IN ('fsutil reparsepoint query "%CheckFolder%"
^| findstr /ic:"Print Name:"') do SET "SymLinkDir=%s"
(IF NOT EXIST "%SymLinkDir%" (echo But the junction's target directory
^("%SymLinkDir%"^) is not existed!) ELSE ( IF EXIST "%SymLinkDir%"
(echo And the junction's target directory ^("%SymLinkDir%"^) is
existed.) ) )
I searched here, found someone using this
set is_dir=0
for %%i in ("%~1") do if exist "%%~si"\nul set is_dir=1
but didn't work, when %1==c:\this is a file with spaces.csproj, the test still success, which means it will still be treated as a folder!!!
anyone knows the answer, i guess this is a very common problem and Windows has existed for many many years, it should have a very simple solution....
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.)
I just tried in this way. Hope this helps.
#ECHO OFF
SET CURR_DIR=%CD%
SET IS_DIR=0
CD %1%
IF "%ERRORLEVEL%"=="0" SET IS_DIR=1
CD %CURR_DIR%
ECHO IS DIRECTORY %IS_DIR%
Output:
D:\Work\Stand alone Java classes>test.bat D:\Work\Training
IS DIRECTORY 1
D:\Work\Stand alone Java classes>test.bat D:\Work\Training\SRT.txt
The directory name is invalid.
IS DIRECTORY 0
The /ad option for "dir" command lists folders, /b option for bare. Assuming you have checks for the existence of file in place, use:
dir /ad /b ChangeThisToYourFilename 1> NUL 2> NUL
if %ERRORLEVEL% EQU 0 (
echo is a file
) else (
echo is NOT a file
)
For a 1 liner:
dir /a:d /b C:\Windows 2>&1 | findstr /i /n /c:"File Not Found">nul && (#echo. Im a file) || (#echo. Im a folder)
e.g. change C:\Windows to C:\Windows\Notepad.exe
-Sorry Arun, dbenham, didn't read yours! Same as..
Previously, I used the "\nul" method, but for a long time now, I have used "\*" to test if an existing filespec is a folder or a file. As far as I know, it works on all versions of Windows, from Windows 95 (and perhaps earlier versions) through all current Windows versions.
So, as with other methods, first test if the file exists. Then, to see if it's a "Folder", test it with: if exist "%fspec%\*":
if not exist "%fspec%" goto :NotExistOrInvalid
rem "%fspec%" is "Valid" and is either a "Folder", or a "File".
if exist "%fspec%\*" goto :IsValidAndIsAFolder
rem "%fspec%" is a "File" (a "Regular File" or a Shortcut/Link).
goto :IsValidAndIsAFile
For example:
set "fspec=XYZ:%perlpath%"
if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem Invalid, goto :NotExistOrInvalid
set "fspec=%perlpath%"
if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem goto :NotExistOrInvalid
rem "%fspec%" Is a "Valid" filespec and is either a "Folder", or a "File".
if exist "%fspec%\*" (echo "%fspec%" is a "Folder".) else echo "%fspec%" is a "File".
set "fspec=%perlpath%\perl.exe"
if not exist "%fspec%" echo "%fspec%": Invalid or not found && rem Invalid, goto :NotExistOrInvalid
rem "%fspec%" Is a "Valid" filespec and is either a "Folder", or a "File".
if exist "%fspec%\*" (echo "%fspec%" is a "Folder".) else echo "%fspec%" is a "File".
The output for this is:
"XYZ:F:\usr\perl\bin": Invalid or not found
"F:\usr\perl\bin" is a "Folder".
"F:\usr\perl\bin\perl.exe" is a "File".
This solution combines the file attribute parameter extension (%~a1) with variable substring extraction (%variable:~0,1%):
#ECHO OFF
CALL :is_directory C:\Windows
CALL :is_directory C:\MinGW\share\doc\mingw-get\README
CALL :is_directory C:\$Recycle.Bin
CALL :is_directory "C:\Documents and Settings"
CALL :is_directory "%LOGONSERVER%\C$\Users\All Users"
GOTO :EOF
:is_directory
SETLOCAL
SET file_attribute=%~a1
IF "%file_attribute:~0,1%"=="d" (
ECHO %file_attribute% %1 is a directory
) ELSE (
ECHO %file_attribute% %1 is NOT a directory
)
ENDLOCAL
GOTO :EOF
Output:
d-------- C:\Windows is a directory
--a------ C:\MinGW\share\doc\mingw-get\README is NOT a directory
d--hs---- C:\$Recycle.Bin is a directory
d--hs---l "C:\Documents and Settings" is a directory
d--hs---l "\\MYCOMPUTER\C$\Users\All Users" is a directory
I have a folder: C:\Folder1
I want to copy all the contents of Folder1 to another location, D:\Folder2
How do I do this using a batch file?
xcopy.exe is the solution here. It's built into Windows.
xcopy /s c:\Folder1 d:\Folder2
You can find more options at http://www.computerhope.com/xcopyhlp.htm
If you have robocopy,
robocopy C:\Folder1 D:\Folder2 /COPYALL /E
otherwise,
xcopy /e /v C:\Folder1 D:\Folder2
I see a lot of answers suggesting the use of xcopy.
But this is unnecessary. As the question clearly mentions that the author wants the content in the folder not the folder itself to be copied in this case we can do
copy "C:\Folder1\*.*" "D:\Folder2"
Thats all xcopy can be used for if any subdirectory exists in C:\Folder1
if you want remove the message that tells if the destination is a file or folder you just add a slash:
xcopy /s c:\Folder1 d:\Folder2\
RoboCopy did not work for me, and there are some good solutions here, but none explained the XCopy switches and what they do. Also you need quotes in case your path has spaces in it.
xcopy /i /e "C:\temp\folder 1" "C:\temp\folder 2"
Here is the documentation from Microsoft:
XCopy MS Documentation
/s: Specifies to include subdirectories. Excludes empty subdirectories
/e: Copies all subdirectories, even if they are empty
/i: specifies the destination is a folder (Otherwise it prompts you)
Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:
robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT
Here:
/COPYALL copies all file information
/E copies subdirectories including empty directories
/IS includes the same files
/IT includes modified files with the same name
For more parameters see the official documentation: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy
Note: it can be necessary to run the command as administrator, because of the argument /COPYALL. If you can't: just get rid of it.
#echo off
::Ask
echo Your Source Path:
set INPUT1=
set /P INPUT1=Type input: %=%
echo Your Destination Path:
set INPUT2=
set /P INPUT2=Type input: %=%
xcopy %INPUT1% %INPUT2% /y /s
On my PC, xcopy and robocopy need also the path to them, i.e. C:\Windows\System32\xcopy.exe
That's why I use simply "copy":
copy /y ....\Folder1\File.txt ....\Folder2\
#echo off
xcopy /s C:\yourfile C:\anotherfile\
This is how it is done!
Simple, right?
FYI...if you use TortoiseSVN and you want to create a simple batch file to xcopy (or directory mirror) entire repositories into a "safe" location on a periodic basis, then this is the specific code that you might want to use. It copies over the hidden directories/files, maintains read-only attributes, and all subdirectories and best of all, doesn't prompt for input. Just make sure that you assign folder1 (safe repo) and folder2 (usable repo) correctly.
#echo off
echo "Setting variables..."
set folder1="Z:\Path\To\Backup\Repo\Directory"
set folder2="\\Path\To\Usable\Repo\Directory"
echo "Removing sandbox version..."
IF EXIST %folder1% (
rmdir %folder1% /s /q
)
echo "Copying official repository into backup location..."
xcopy /e /i /v /h /k %folder2% %folder1%
And, that's it folks!
Add to your scheduled tasks and never look back.
I have written a .bat file to copy and paste file to a temporary folder and make it zip and transfer into a smb mount point,
Hope this would help,
#echo off
if not exist "C:\Temp Backup\" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
xcopy /s/e/q "C:\Source" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\TELIUM"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_Log_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
NET USE \\IP\IPC$ /u:IP\username password
ROBOCOPY "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" "\\IP\Backup Folder" /z /MIR /unilog+:"C:\backup_log_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log"
NET USE \\172.20.10.103\IPC$ /D
RMDIR /S /Q "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
#echo off
:: variables
echo Backing up file
set /P source=Enter source folder:
set /P destination=Enter Destination folder:
set xcopy=xcopy /S/E/V/Q/F/H/I/N
%xcopy% %source% %destination%
echo files will be copy press enter to proceed
pause
I have to create a .BAT file that does this:
If C:\myprogram\sync\data.handler exists, exit;
If C:\myprogram\html\data.sql does not exist, exit;
In C:\myprogram\sync\ delete all files and folders except (test, test3 and test2)
Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
Call other batch file with option sync.bat myprogram.ini.
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You can use IF EXIST to check for a file:
IF EXIST "filename" (
REM Do one thing
) ELSE (
REM Do another thing
)
If you do not need an "else", you can do something like this:
set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=
Here's a working example of searching for a file or a folder:
REM setup
echo "some text" > filename
mkdir "foldername"
REM finds file
IF EXIST "filename" (
ECHO file filename exists
) ELSE (
ECHO file filename does not exist
)
REM does not find file
IF EXIST "filename2.txt" (
ECHO file filename2.txt exists
) ELSE (
ECHO file filename2.txt does not exist
)
REM folders must have a trailing backslash
REM finds folder
IF EXIST "foldername\" (
ECHO folder foldername exists
) ELSE (
ECHO folder foldername does not exist
)
REM does not find folder
IF EXIST "filename\" (
ECHO folder filename exists
) ELSE (
ECHO folder filename does not exist
)
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not
know how to test if a file or folder exists and if it is a file or
folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
Is there any way to find out if a file is a directory?
I have the file name in a variable. In Perl I can do this:
if(-d $var) { print "it's a directory\n" }
This works:
if exist %1\* echo Directory
Works with directory names that contains spaces:
C:\>if exist "c:\Program Files\*" echo Directory
Directory
Note that the quotes are necessary if the directory contains spaces:
C:\>if exist c:\Program Files\* echo Directory
Can also be expressed as:
C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory
This is safe to try at home, kids!
Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the files attributes and cut first char
#echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF
You can do it like so:
IF EXIST %VAR%\NUL ECHO It's a directory
However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:
FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.
(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)
Further to my previous offering, I find this also works:
if exist %1\ echo Directory
No quotes around %1 are needed because the caller will supply them.
This saves one entire keystroke over my answer of a year ago ;-)
Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.
#echo off
if [%1]==[] goto usage
for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir
:notdir
echo not a directory
goto exit
:isdir
popd
echo is a directory
goto exit
:usage
echo Usage: %0 DIRECTORY_TO_TEST
:exit
Sample output with the above saved as "isdir.bat":
C:\>isdir c:\Windows\system32
is a directory
C:\>isdir c:\Windows\system32\wow32.dll
not a directory
C:\>isdir c:\notadir
not a directory
C:\>isdir "C:\Documents and Settings"
is a directory
C:\>isdir \
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory
This works perfectly
if exist "%~1\" echo Directory
we need to use %~1 to remove quotes from %1, and add a backslash at end. Then put thw whole into qutes again.
CD returns an EXIT_FAILURE when the specified directory does not exist. And you got conditional processing symbols, so you could do like the below for this.
SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error
:Error
CD %cd_backup%
A variation of #batchman61's approach (checking the Directory attribute).
This time I use an external 'find' command.
(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)
#ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
ECHO %1 is a directory
)
Outputs yes on:
Directories.
Directory symbolic links or junctions.
Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
Directories which you have no read permission on (e.g. "C:\System Volume Information")
The NUL technique seems to only work on 8.3 compliant file names.
(In other words, `D:\Documents and Settings` is "bad" and `D:\DOCUME~1` is "good")
I think there is some difficulty using the "NUL" tecnique when there are SPACES in the directory name, such as "Documents and Settings."
I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe
Here are some examples of what DID NOT work and what DOES WORK for me:
(These are all demonstrations done "live" at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)
This DID NOT work:
D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes
This DID NOT work:
D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes
This DOES work (for me):
D:\Documents and Settings>cd ..
D:\>REM get the short 8.3 name for the file
D:\>dir /x
Volume in drive D has no label.
Volume Serial Number is 34BE-F9C9
Directory of D:\
09/25/2008 05:09 PM <DIR> 2008
09/25/2008 05:14 PM <DIR> 200809~1.25 2008.09.25
09/23/2008 03:44 PM <DIR> BOOST_~3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME~1.EXE ChromeSetup.exe
02/14/2008 12:32 PM <DIR> cygwin
[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings
09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM <DIR> NATION~1 National Instruments Downloads
10/12/2007 11:25 AM <DIR> NVIDIA
05/13/2008 09:42 AM <DIR> Office10
09/19/2008 11:08 AM <DIR> PROGRA~1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM <DIR> TEMP
02/14/2008 12:26 PM <DIR> tmp
01/21/2008 07:05 PM <DIR> VXIPNP
09/23/2008 12:15 PM <DIR> WINDOWS
02/21/2008 03:49 PM <DIR> wx28
02/29/2008 01:47 PM <DIR> WXWIDG~2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free
D:\>REM now use the \NUL test with the 8.3 name
D:\>if exist d:\docume~1\NUL echo yes
yes
This works, but it's sort of silly, because the dot already implies i am in a directory:
D:\Documents and Settings>if exist .\NUL echo yes
I use this:
if not [%1] == [] (
pushd %~dpn1 2> nul
if errorlevel == 1 pushd %~dp1
)
This works and also handles paths with spaces in them:
dir "%DIR%" > NUL 2>&1
if not errorlevel 1 (
echo Directory exists.
) else (
echo Directory does not exist.
)
Probably not the most efficient but easier to read than the other solutions in my opinion.
A very simple way is to check if the child exists.
If a child does not have any child, the exist command will return false.
IF EXIST %1\. (
echo %1 is a folder
) else (
echo %1 is a file
)
You may have some false negative if you don't have sufficient access right (I have not tested it).
If you can cd into it, it's a directory:
set cwd=%cd%
cd /D "%1" 2> nul
#IF %errorlevel%==0 GOTO end
cd /D "%~dp1"
#echo This is a file.
#goto end2
:end
#echo This is a directory
:end2
#REM restore prior directory
#cd %cwd%
Based on this article titled "How can a batch file test existence of a directory" it's "not entirely reliable".
BUT I just tested this:
#echo off
IF EXIST %1\NUL goto print
ECHO not dir
pause
exit
:print
ECHO It's a directory
pause
and it seems to work
Here's my solution:
REM make sure ERRORLEVEL is 0
TYPE NUL
REM try to PUSHD into the path (store current dir and switch to another one)
PUSHD "insert path here..." >NUL 2>&1
REM if ERRORLEVEL is still 0, it's most definitely a directory
IF %ERRORLEVEL% EQU 0 command...
REM if needed/wanted, go back to previous directory
POPD
I would like to post my own function script about this subject hope to be useful for someone one day.
#pushd %~dp1
#if not exist "%~nx1" (
popd
exit /b 0
) else (
if exist "%~nx1\*" (
popd
exit /b 1
) else (
popd
exit /b 3
)
)
This batch script checks if file/folder is exist and if it is a file or a folder.
Usage:
script.bat "PATH"
Exit code(s):
0: file/folder doesn't exist.
1: exists, and it is a folder.
3: exists, and it is a file.
Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:
#echo off
if exist c:\temp\data.csv echo data.csv is a file
if exist c:\temp\data.csv\ echo data.csv is a directory
if exist c:\temp\data.csv\nul echo data.csv is a directory
if exist k:\temp\nonexistent.txt echo nonexistent.txt is a file
if exist k:\temp\something.txt echo something.txt is a file
if exist k:\temp\something.txt\ echo something.txt is a directory
if exist k:\temp\something.txt\nul echo something.txt is a directory
produces:
data.csv is a file
something.txt is a file
something.txt is a directory
something.txt is a directory
So beware if your script might be fed a mapped or UNC path. The pushd solution below seems to be the most foolproof.
This is the code that I use in my BATCH files
```
#echo off
set param=%~1
set tempfile=__temp__.txt
dir /b/ad > %tempfile%
set isfolder=false
for /f "delims=" %%i in (temp.txt) do if /i "%%i"=="%param%" set isfolder=true
del %tempfile%
echo %isfolder%
if %isfolder%==true echo %param% is a directory
```
Here is my solution after many tests with if exist, pushd, dir /AD, etc...
#echo off
cd /d C:\
for /f "delims=" %%I in ('dir /a /ogn /b') do (
call :isdir "%%I"
if errorlevel 1 (echo F: %%~fI) else echo D: %%~fI
)
cmd/k
:isdir
echo.%~a1 | findstr /b "d" >nul
exit /b %errorlevel%
:: Errorlevel
:: 0 = folder
:: 1 = file or item not found
It works with files that have no extension
It works with folders named folder.ext
It works with UNC path
It works with double-quoted full path or with just the dirname or filename only.
It works even if you don't have read permissions
It works with Directory Links (Junctions).
It works with files whose path contains a Directory Link.
One issue with using %%~si\NUL method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.
An alternative method:
dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)
:IsFile
echo %F% is a file
goto done
:IsDir
echo %F% is a directory
goto done
:done
You can replace (goto IsFile)||(goto IsDir) with other batch commands:
(echo Is a File)||(echo is a Directory)
If your objective is to only process directories then this will be useful.
This is taken from the https://ss64.com/nt/for_d.html
Example... List every subfolder, below the folder C:\Work\ that has a name starting with "User":
CD \Work
FOR /D /r %%G in ("User*") DO Echo We found
FOR /D or FOR /D /R
#echo off
cd /d "C:\your directory here"
for /d /r %%A in ("*") do echo We found a folder: %%~nxA
pause
Remove /r to only go one folder deep. The /r switch is recursive and undocumented in the command below.
The for /d help taken from command for /?
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
I was looking for this recently as well, and had stumbled upon a solution which has worked for me, but I do not know of any limitations it has (as I have yet to discover them). I believe this answer is similar in nature to TechGuy's answer above, but I want to add another level of viability. Either way, I have had great success expanding the argument into a full fledged file path, and I believe you have to use setlocal enableextensions for this to work properly.
Using below I can tell if a file is a directory, or opposite. A lot of this depends on what the user is actually needing. If you prefer to work with a construct searching for errorlevel vs && and || in your work you can of course do so. Sometimes an if construct for errorlevel can give you a little more flexibility since you do not have to use a GOTO command which can sometimes break your environment conditions.
#Echo Off
setlocal enableextensions
Dir /b /a:D "%~f1" && Echo Arg1 is a Folder || Echo Arg1 is NOT a Folder
Dir /b /a:-D "%~f1" && Echo Arg1 is a File || Echo Arg1 is NOT a File
pause
Using this you could simply drag and drop your file(s) onto the tool you are building to parse them out. Conversely, if you are using other means to comb your file structure and you already have the file and are not dragging/dropping them onto the batch file, you could implement this:
#Echo Off
setlocal enableextensions
Dir /b /s "C:\SomeFolderIAmCombing\*" >"%~dp0SomeFiletogoThroughlater.txt"
For /f "Usebackq Delims=" %%a in ("%~dp0SomeFiletogoThroughlater.txt") do (
Call:DetectDir "%%a"
)
REM Do some stuff after parsing through Files/Directories if needed.
REM GOTO:EOF below is used to skip all the subroutines below.
REM Using ' CALL:DetectDir "%%a" ' with the for loop keeps the for
REM loop environment running in the background while still parsing the given file
REM in a clean environment where GOTO and other commmands do not need Variable Expansion.
GOTO:EOF
:DetectDir [File or Folder being checked]
REM Checks if Arg1 is a Directory. If yes, go to Dir coding. If not, go to File coding.
Dir /b /a:D "%~f1" && Echo Arg1 is a Folder & GOTO:IsDir || Echo Arg1 is NOT a Folder & GOTO:IsFile
REM Checks if Arg1 is NOT a Directory. If Yes, go to File coding. If not, go to Dir coding
Dir /b /a:-D "%~f1" && Echo Arg1 is a File & GOTO:IsFile || Echo Arg1 is NOT a File & GOTO:IsDir
:IsDir
REM Do your stuff to the Folder
GOTO:EOF
:IsFile
REM do your stuff to the File
GOTO:EOF
Can't we just test with this :
IF [%~x1] == [] ECHO Directory
It seems to work for me.