windows 使用命令行删除目录及其文件,但如果不存在则不抛出错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14502612/
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 10:13:08  来源:igfitidea点击:

Delete a directory and its files using command line but don't throw error if it doesn't exist

windowsbatch-filecmd

提问by jaywayco

I need a Windows command to delete a directory and all its containing files but I do not want to see any errors if the directory does not exist.

我需要一个 Windows 命令来删除一个目录及其所有包含的文件,但如果该目录不存在,我不希望看到任何错误。

采纳答案by GolezTrol

Redirect the output of the delcommand to nul. Note the 2, to indicate error output should be redirected. See also this question, and especially the tech doc Using command redirection operators.

del命令的输出重定向到 nul。请注意2, 以指示应重定向错误输出。另请参阅此问题,尤其是使用命令重定向操作符的技术文档。

del {whateveroptions} 2>nul

Or you can check for file existence before calling del:

或者您可以在调用之前检查文件是否存在del

if exist c:\folder\file del c:\folder\file

Note that you can use if exist c:\folder\(with the trailing \) to check if c:\folderis indeed a folder and not a file.

请注意,您可以使用if exist c:\folder\(带有尾随\)来检查是否c:\folder确实是文件夹而不是文件。

回答by dbenham

Either redirect stderr to nul

要么将 stderr 重定向到 nul

rd /q /s "c:\yourFolder" 2>nul

Or verify that folder exists before deleting. Note that the trailing \is critical in the IF condition.

或者在删除之前验证该文件夹是否存在。请注意,尾随\在 IF 条件下至关重要。

if exist "c:\yourFolder\" rd /q /s "c:\yourFolder"

回答by christopher2007

For me on Windows 10 the following is working great:

对我来说,在 Windows 10 上,以下工作很好:

if exist <path> rmdir <path> /q /s

qstands for "delete without asking" and sstands for "delete all subfolders and files in it".

q代表“不问就删除”,s代表“删除其中的所有子文件夹和文件”。

And you can also concatinate the command:

您还可以连接命令:

(if exist <path> rmdir <path> /q /s) && <some other command that executes after deleting>

回答by Bali C

You can redirect stderr to nul

您可以将 stderr 重定向到 nul

del filethatdoesntexist.txt 2>nul

回答by Anjana Silva

The above comes up with Y or N in the prompt. So, I used the following instead and it works perfectly.

以上在提示中出现了 Y 或 N。所以,我改用了以下内容,并且效果很好。

if exist cddd rmdir cddd

Hope this helps someone.

希望这可以帮助某人。

Cheers.

干杯。