如何测试文件是否是批处理脚本中的目录?

时间:2023-01-18 02:23:45

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:

我在变量中有文件名。在Perl中,我可以这样做:

if(-d $var) { print "it's a directory\n" }

22 个解决方案

#1


45  

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:

但是,这仅适用于名称中没有空格的目录。当您在变量周围添加引号以处理空格时,它将停止工作。要处理带空格的目录,请将文件名转换为短8.3格式,如下所示:

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.

%% ~si将%% i转换为8.3文件名。要查看可以使用FOR变量执行的所有其他技巧,请在命令提示符处输入HELP FOR。

(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.)

(注意 - 上面给出的示例是在批处理文件中使用的格式。要在命令行中使用它,请在两个位置替换%%和%。)

#2


77  

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!

孩子们在家里试试这是安全的!

#3


42  

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

最近因上述不同方法而失败。相当肯定他们过去工作过,也许与dfs有关。现在使用files属性并剪切第一个char

@echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF

#4


11  

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 ;-)

不需要%1周围的引号,因为调用者将提供它们。这比一年前的答案节省了一整个击键;-)

#5


9  

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.

这是一个脚本,它使用FOR来构建一个完全限定的路径,然后推送以测试路径是否是一个目录。请注意它如何适用于包含空格的路径以及网络路径。

@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":

上面的示例输出保存为“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

#6


6  

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.

我们需要使用%~1来删除%1中的引号,并在结尾处添加反斜杠。然后再将整体放入qutes中。

#7


3  

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."

我认为当目录名称中有SPACES时,使用“NUL”tecnique有一些困难,例如“Documents and Settings”。

I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe

我正在使用Windows XP Service Pack 2并从%SystemRoot%\ system32 \ cmd.exe启动cmd提示符

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:

这个DID不起作用:

D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes

D:\ Documents and Settings>如果存在“D:\ Documents and Settings \ NUL”则回显是

This DID NOT work:

这个DID不起作用:

D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes

D:\ Documents and Settings>如果存在D:\ Documents and Settings \ NUL echo yes

This DOES work (for me):

这对我有用(对我来说):

D:\Documents and Settings>cd ..

D:\ Documents and Settings> cd ..

D:\>REM get the short 8.3 name for the file

D:\> REM获取文件的短8.3名称

D:\>dir /x

Volume in drive D has no label. Volume Serial Number is 34BE-F9C9

驱动器D中的卷没有标签。卷序列号为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

目录D:\ 09/25/2008 05:09 PM

2008 09/25/2008 05:14 PM 200809~1.25 2008.09.25 09/23/2008 03:44 PM 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 cygwin

[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings

[[看这里!!!! ]] 2008年9月25日上午08:34

DOCUME~1文件和设置

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

09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt 01/21/2008 06:58 PM

NATION~1 National Instruments下载10/12/2007 11:25 AM NVIDIA 05 / 13/2008 09:42 AM Office10 09/19/2008 11:08 AM PROGRA~1 Program Files 12/02/1999 02:54 PM 24,576 setx.exe 09/15/2008 11:19 AM TEMP 02/14/2008 12:26 PM tmp 01/21/2008 07:05 PM VXIPNP 09/23/2008 12:15 PM WINDOWS 02/21/2008 03 :下午49点 wx28 02/29/2008 01:47 PM WXWIDG~2 wxWidgets 3个文件510,704个字节20个Dir(s)238,250,901,504个字节免费

D:\>REM now use the \NUL test with the 8.3 name

D:\> REM现在使用带有8.3名称的\ NUL测试

D:\>if exist d:\docume~1\NUL echo yes

D:\>如果存在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

D:\ Documents and Settings>如果存在。\ NUL echo yes

#8


3  

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.

在我看来,可能不是最有效但更容易阅读的其他解决方案。

#9


3  

A variation of @batchman61's approach (checking the Directory attribute).

@ batchman61方法的变体(检查目录属性)。

This time I use an external 'find' command.

这次我使用外部'find'命令。

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

(哦,注意&&技巧。这是为了避免长期无聊的IF ERRORLEVEL语法。)

@ECHO OFF
SETLOCAL EnableExtentions
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")
  • 您没有读取权限的目录(例如“C:\ System Volume Information”)

#10


2  

I use this:

我用这个:

if not [%1] == [] (
  pushd %~dpn1 2> nul
  if errorlevel == 1 pushd %~dp1
)

#11


2  

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.

如果孩子没有孩子,则exists命令将返回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).

如果您没有足够的访问权限(我还没有测试过),您可能会有一些误报。

#12


1  

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

它似乎工作

#13


1  

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

#14


1  

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%

#15


1  

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.

0:文件/文件夹不存在。

1: exists, and it is a folder.

1:存在,它是一个文件夹。

3: exists, and it is a file.

3:存在,它是一个文件。

#16


0  

Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:

在Windows 7和XP下,我无法让它在映射驱动器上告诉文件与dirs。以下脚本:

@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.

因此,请注意您的脚本是否可以提供映射或UNC路径。下面的推动解决方案似乎是最简单的。

#17


0  

This is the code that I use in my BATCH files

这是我在BATCH文件中使用的代码

```
@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

```

#18


0  

Ok... the 'nul' trick doesn't work if you use quotes in names, which accounts for most files with long file names or spaces.

好的...如果在名称中使用引号,那么'nul'技巧不起作用,这会占大多数具有长文件名或空格的文件。

For example,

if exist "C:\nul" echo Directory

does nothing, but

什么都不做,但是

if exist C:\nul echo Directory

works.

I finally came up with this, which seemed to work for all cases:

我终于想出了这个,这似乎适用于所有情况:

for /f %%i in ('DIR /A:D /B %~dp1 ^| findstr /X /c:"%~nx1"') do echo Directory

or if you can assure you meet all of the requirements for 'nul' a solution is:

或者,如果您能确保满足'nul'的所有要求,则解决方案是:

if exist %~sf1\nul echo Directory

Put these into a batch file like 'test.bat' and do 'test.bat MyFile'.

将这些放入像'test.bat'这样的批处理文件中并执行'test.bat MyFile'。

#19


0  

Here is my solution after many tests with if exist, pushd, dir /AD, etc...

这是我的解决方案经过多次测试后,如果存在,pushd,dir / AD等...

@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
  • 它适用于名为folder.ext的文件夹

  • It works with UNC path
  • 它适用于UNC路径

  • It works with double-quoted full path or with just the dirname or filename only.
  • 它适用于双引号完整路径或仅使用dirname或文件名。

  • 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.
  • 它适用于路径包含目录链接的文件。

#20


0  

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.

使用%% ~si \ NUL方法的一个问题是它有可能猜错了。它可能有一个文件名缩短到错误的文件。我不认为%% ~si解析8.3文件名,但猜测它,但使用字符串操作来缩短文件路径。我相信如果你有类似的文件路径,它可能无法正常工作。

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)

你可以用其他批处理命令替换(转到IsFile)||(转到IsDir):( echo is a File)||(echo是一个目录)

#21


0  

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.

当指定的目录不存在时,CD返回EXIT_FAILURE。并且你有条件处理符号,所以你可以像下面这样做。

SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error

:Error
CD %cd_backup%

#22


-2  

Can't we just test with this :

我们不能只用这个来测试:

IF [%~x1] == [] ECHO Directory

It seems to work for me.

它似乎对我有用。

#1


45  

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:

但是,这仅适用于名称中没有空格的目录。当您在变量周围添加引号以处理空格时,它将停止工作。要处理带空格的目录,请将文件名转换为短8.3格式,如下所示:

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.

%% ~si将%% i转换为8.3文件名。要查看可以使用FOR变量执行的所有其他技巧,请在命令提示符处输入HELP FOR。

(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.)

(注意 - 上面给出的示例是在批处理文件中使用的格式。要在命令行中使用它,请在两个位置替换%%和%。)

#2


77  

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!

孩子们在家里试试这是安全的!

#3


42  

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

最近因上述不同方法而失败。相当肯定他们过去工作过,也许与dfs有关。现在使用files属性并剪切第一个char

@echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF

#4


11  

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 ;-)

不需要%1周围的引号,因为调用者将提供它们。这比一年前的答案节省了一整个击键;-)

#5


9  

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.

这是一个脚本,它使用FOR来构建一个完全限定的路径,然后推送以测试路径是否是一个目录。请注意它如何适用于包含空格的路径以及网络路径。

@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":

上面的示例输出保存为“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

#6


6  

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.

我们需要使用%~1来删除%1中的引号,并在结尾处添加反斜杠。然后再将整体放入qutes中。

#7


3  

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."

我认为当目录名称中有SPACES时,使用“NUL”tecnique有一些困难,例如“Documents and Settings”。

I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe

我正在使用Windows XP Service Pack 2并从%SystemRoot%\ system32 \ cmd.exe启动cmd提示符

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:

这个DID不起作用:

D:\Documents and Settings>if exist "D:\Documents and Settings\NUL" echo yes

D:\ Documents and Settings>如果存在“D:\ Documents and Settings \ NUL”则回显是

This DID NOT work:

这个DID不起作用:

D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes

D:\ Documents and Settings>如果存在D:\ Documents and Settings \ NUL echo yes

This DOES work (for me):

这对我有用(对我来说):

D:\Documents and Settings>cd ..

D:\ Documents and Settings> cd ..

D:\>REM get the short 8.3 name for the file

D:\> REM获取文件的短8.3名称

D:\>dir /x

Volume in drive D has no label. Volume Serial Number is 34BE-F9C9

驱动器D中的卷没有标签。卷序列号为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

目录D:\ 09/25/2008 05:09 PM

2008 09/25/2008 05:14 PM 200809~1.25 2008.09.25 09/23/2008 03:44 PM 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 cygwin

[[Look right here !!!! ]]
09/25/2008 08:34 AM <DIR> DOCUME~1 Documents and Settings

[[看这里!!!! ]] 2008年9月25日上午08:34

DOCUME~1文件和设置

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

09/11/2008 01:57 PM 0 EMPTY_~1.TXT empty_testcopy_file.txt 01/21/2008 06:58 PM

NATION~1 National Instruments下载10/12/2007 11:25 AM NVIDIA 05 / 13/2008 09:42 AM Office10 09/19/2008 11:08 AM PROGRA~1 Program Files 12/02/1999 02:54 PM 24,576 setx.exe 09/15/2008 11:19 AM TEMP 02/14/2008 12:26 PM tmp 01/21/2008 07:05 PM VXIPNP 09/23/2008 12:15 PM WINDOWS 02/21/2008 03 :下午49点 wx28 02/29/2008 01:47 PM WXWIDG~2 wxWidgets 3个文件510,704个字节20个Dir(s)238,250,901,504个字节免费

D:\>REM now use the \NUL test with the 8.3 name

D:\> REM现在使用带有8.3名称的\ NUL测试

D:\>if exist d:\docume~1\NUL echo yes

D:\>如果存在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

D:\ Documents and Settings>如果存在。\ NUL echo yes

#8


3  

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.

在我看来,可能不是最有效但更容易阅读的其他解决方案。

#9


3  

A variation of @batchman61's approach (checking the Directory attribute).

@ batchman61方法的变体(检查目录属性)。

This time I use an external 'find' command.

这次我使用外部'find'命令。

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

(哦,注意&&技巧。这是为了避免长期无聊的IF ERRORLEVEL语法。)

@ECHO OFF
SETLOCAL EnableExtentions
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")
  • 您没有读取权限的目录(例如“C:\ System Volume Information”)

#10


2  

I use this:

我用这个:

if not [%1] == [] (
  pushd %~dpn1 2> nul
  if errorlevel == 1 pushd %~dp1
)

#11


2  

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.

如果孩子没有孩子,则exists命令将返回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).

如果您没有足够的访问权限(我还没有测试过),您可能会有一些误报。

#12


1  

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

它似乎工作

#13


1  

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

#14


1  

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%

#15


1  

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.

0:文件/文件夹不存在。

1: exists, and it is a folder.

1:存在,它是一个文件夹。

3: exists, and it is a file.

3:存在,它是一个文件。

#16


0  

Under Windows 7 and XP, I can't get it to tell files vs. dirs on mapped drives. The following script:

在Windows 7和XP下,我无法让它在映射驱动器上告诉文件与dirs。以下脚本:

@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.

因此,请注意您的脚本是否可以提供映射或UNC路径。下面的推动解决方案似乎是最简单的。

#17


0  

This is the code that I use in my BATCH files

这是我在BATCH文件中使用的代码

```
@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

```

#18


0  

Ok... the 'nul' trick doesn't work if you use quotes in names, which accounts for most files with long file names or spaces.

好的...如果在名称中使用引号,那么'nul'技巧不起作用,这会占大多数具有长文件名或空格的文件。

For example,

if exist "C:\nul" echo Directory

does nothing, but

什么都不做,但是

if exist C:\nul echo Directory

works.

I finally came up with this, which seemed to work for all cases:

我终于想出了这个,这似乎适用于所有情况:

for /f %%i in ('DIR /A:D /B %~dp1 ^| findstr /X /c:"%~nx1"') do echo Directory

or if you can assure you meet all of the requirements for 'nul' a solution is:

或者,如果您能确保满足'nul'的所有要求,则解决方案是:

if exist %~sf1\nul echo Directory

Put these into a batch file like 'test.bat' and do 'test.bat MyFile'.

将这些放入像'test.bat'这样的批处理文件中并执行'test.bat MyFile'。

#19


0  

Here is my solution after many tests with if exist, pushd, dir /AD, etc...

这是我的解决方案经过多次测试后,如果存在,pushd,dir / AD等...

@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
  • 它适用于名为folder.ext的文件夹

  • It works with UNC path
  • 它适用于UNC路径

  • It works with double-quoted full path or with just the dirname or filename only.
  • 它适用于双引号完整路径或仅使用dirname或文件名。

  • 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.
  • 它适用于路径包含目录链接的文件。

#20


0  

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.

使用%% ~si \ NUL方法的一个问题是它有可能猜错了。它可能有一个文件名缩短到错误的文件。我不认为%% ~si解析8.3文件名,但猜测它,但使用字符串操作来缩短文件路径。我相信如果你有类似的文件路径,它可能无法正常工作。

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)

你可以用其他批处理命令替换(转到IsFile)||(转到IsDir):( echo is a File)||(echo是一个目录)

#21


0  

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.

当指定的目录不存在时,CD返回EXIT_FAILURE。并且你有条件处理符号,所以你可以像下面这样做。

SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error

:Error
CD %cd_backup%

#22


-2  

Can't we just test with this :

我们不能只用这个来测试:

IF [%~x1] == [] ECHO Directory

It seems to work for me.

它似乎对我有用。