windows 使用 .bat 文件检查文件夹是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21033801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:14:38  来源:igfitidea点击:

Checking if a folder exists using a .bat file

windowsbatch-file

提问by user3179825

I would like to be able to check if a certain folder (FolderA) exists and if so, for a message to be displayed and then the batch file to be exited.

我希望能够检查某个文件夹 (FolderA) 是否存在,如果存在,则显示一条消息,然后退出批处理文件。

If FolderA does not exist, I would then like to check if another folder (FolderB) exists. If FolderB does not exist, a message should be displayed and the folder should be created, and if FolderB does exist, a message should be displayed saying so.

如果 FolderA 不存在,我想检查是否存在另一个文件夹(FolderB)。如果 FolderB 不存在,则应显示一条消息并应创建该文件夹,如果 FolderB 确实存在,则应显示一条消息说明存在。

Does anybody have any idea on the code I could simply use on notepad to create a batch file to allow me to do this?

有没有人对我可以简单地在记事本上使用以创建批处理文件以允许我执行此操作的代码有任何想法?

All of this needs to be done in one .batfile.

所有这些都需要在一个.bat文件中完成。

回答by 09stephenb

Try using this:

尝试使用这个:

IF EXIST yourfilename (
echo Yes 
) ELSE (
echo No
)

Replace yourfilenamewith the name of your file.

yourfilename替换为您的文件名。

For a directory look at this https://jeffpar.github.io/kbarchive/kb/065/Q65994/

有关目录,请查看此https://jeffpar.github.io/kbararchive/kb/065/Q65994/

C:
IF NOT EXIST C:\WIN\ GOTO NOWINDIR
CD \WIN
:NOWINDIR

trailing backslash ('\') seems to be enough to distinguish between directories and ordinary files.

尾随反斜杠 ('\') 似乎足以区分目录和普通文件。

回答by Cosmin Van?

I think the answer is here (possibly duplicate):

我认为答案在这里(可能重复):

How to test if a file is a directory in a batch script?

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

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

将 %VAR% 替换为您的目录。请阅读原始答案,因为包含有关处理文件夹名称中空格的详细信息。

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

正如 foxidrive 所说,这在 NT 类窗口上可能不可靠。它对我有用,但我知道它有一些限制(您可以在参考问题中找到)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

对于现代窗户来说应该足够了。