如何在 Windows 中的命令提示符下删除特定目录中的文件/子文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1965787/
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
How to delete files/subfolders in a specific directory at the command prompt in Windows
提问by Deniz Zoeteman
Say, there is a variable called %pathtofolder%
, as it makes it clear it is a full path of a folder.
比如说,有一个名为 的变量%pathtofolder%
,因为它清楚地表明它是文件夹的完整路径。
I want to delete every single file and subfolder in this directory, but not the directory itself.
我想删除此目录中的每个文件和子文件夹,但不删除目录本身。
But, there might be an error like 'this file/folder is already in use'... when that happens, it should just continue and skip that file/folder.
但是,可能会出现“此文件/文件夹已在使用中”之类的错误……发生这种情况时,它应该继续并跳过该文件/文件夹。
Is there some command for this?
有什么命令吗?
采纳答案by Iain
You can use this shell script to clean up the folder and files within C:\Temp
source:
您可以使用此 shell 脚本来清理C:\Temp
source 中的文件夹和文件:
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat
创建一个包含上述命令的批处理文件(例如,delete.bat)。到delete.bat文件所在的位置,然后运行命令:delete.bat
回答by Suresh
rmdir
is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.
rmdir
是我最喜欢的工作命令。它适用于删除带有子文件夹的大文件和文件夹。未创建备份,因此请确保在运行此命令之前已安全复制文件。
RMDIR "FOLDERNAME" /S /Q
This silently removes the folder and all files and subfolders.
这会以静默方式删除文件夹以及所有文件和子文件夹。
回答by wojciech_rak
The simplest solution I can think of is removing the whole directory with
我能想到的最简单的解决方案是删除整个目录
RD /S /Q folderPath
Then creating this directory again:
然后再次创建此目录:
MD folderPath
回答by foxidrive
This will remove the folders and files and leave the folder behind.
这将删除文件夹和文件并将文件夹留在后面。
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
回答by thepip3r
@ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
@ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.
...删除给定目录下的所有文件和文件夹,但不删除目录本身。
回答by O.Badr
CD [Your_Folder]
RMDIR /S /Q .
You'll get an error message, tells you that the RMDIR command can't access the current folder, thus it can't delete it.
您将收到一条错误消息,告诉您 RMDIR 命令无法访问当前文件夹,因此无法删除它。
Update:
更新:
From thisuseful comment (thanks to Moritz Both), you may add &&
between, so RMDIR
won't run if the CD
command fails (e.g. mistyped directory name):
从这个有用的评论(感谢Moritz Both),您可以在&&
两者之间添加,因此RMDIR
如果CD
命令失败(例如输入错误的目录名称)将不会运行:
CD [Your_Folder] && RMDIR /S /Q .
From Windows Command-Line Reference:
/S:Deletes a directory tree (the specified directory and all its subdirectories, including all files).
/Q:Specifies quiet mode. Does not prompt for confirmation when deleting a directory tree. (Note that /q works only if /s is specified.)
/S:删除目录树(指定目录及其所有子目录,包括所有文件)。
/Q:指定安静模式。删除目录树时不提示确认。(请注意,/q 仅在指定了 /s 时才有效。)
回答by Sireesh Yarlagadda
RD stands for REMOVE Directory.
RD 代表删除目录。
/S : Delete all files and subfolders in addition to the folder itself. Use this to remove an entire folder tree.
/S :删除除文件夹本身之外的所有文件和子文件夹。使用它来删除整个文件夹树。
/Q : Quiet - do not display YN confirmation
/Q : Quiet - 不显示 YN 确认
Example :
例子 :
RD /S /Q C:/folder_path/here
回答by rhellem
I use Powershell
我使用 Powershell
Remove-Item c:\scripts\* -recurse
It will remove the contents of the folder, not the folder itself.
它将删除文件夹的内容,而不是文件夹本身。
回答by Mofi
None of the answers as posted on 2018-06-01, with the exceptionof the single command line posted by foxidrive, really deleted all files and all folders/directories in %PathToFolder%
. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DELand FORwith RDfailed to clean up a folder completely.
除了foxidrive发布的单个命令行外,2018-06-01 上发布的所有答案都没有真正删除%PathToFolder%
. 这就是使用非常简单的单个命令行发布更多答案以删除文件夹的所有文件和子文件夹以及具有更复杂解决方案的批处理文件的原因,解释了为什么使用DEL在 2018-06-01 发布的所有其他答案和FOR与RD未能彻底清理的文件夹。
The simple single command line solution which of course can be also used in a batch file:
简单的单命令行解决方案,当然也可以在批处理文件中使用:
pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )
This command line contains three commands executed one after the other.
该命令行包含三个依次执行的命令。
The first command PUSHDpushes current directory path on stack and next makes %PathToFolder%
the current directory for running command process.
第一个命令PUSHD将当前目录路径推入堆栈,然后创建%PathToFolder%
当前目录以运行命令进程。
This works also for UNCpaths by default because of command extensions are enabled by default and in this case PUSHDcreates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.
默认情况下,这也适用于UNC路径,因为默认情况下启用命令扩展,在这种情况下,PUSHD创建一个指向指定网络资源的临时驱动器号,然后使用新定义的驱动器号更改当前驱动器和目录。
PUSHDoutputs following error message to handle STDERRif the specified directory does not exist at all:
如果指定的目录根本不存在,PUSHD 会输出以下错误消息来处理STDERR:
The system cannot find the path specified.
该系统找不到指定的路径。
This error message is suppressed by redirecting it with 2>nul
to device NUL.
通过将其重定向2>nul
到设备NUL来抑制此错误消息。
The next command RDis executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.
只有当当前命令进程的当前目录更改为指定目录成功,即指定目录完全存在时,才会执行下一个命令RD。
The command RDwith the options /Q
and /S
removes a directory quietlywith all subdirectorieseven if the specified directory contains files or folders with hidden attribute or with?read-only attribute set. The system attribute does never prevent deletion of a file or folder.
该命令RD与选择/Q
和/S
删除一个目录悄悄所有子目录即使指定的目录中,有隐藏属性或文件或文件夹?只读属性集。系统属性永远不会阻止删除文件或文件夹。
Not deleted are:
未删除的有:
Folders used as the current directory for any running process. The entire folder tree to such a?folder cannot be deleted if a folder is used as the current directory for any running process.
Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.
Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.
用作任何正在运行的进程的当前目录的文件夹。如果某个文件夹用作任何正在运行的进程的当前目录,则无法删除该文件夹的整个文件夹树。
当前由任何正在运行的进程打开的文件,在文件打开时设置了文件访问权限,以防止在运行的应用程序/进程打开时删除文件。这样一个打开的文件也防止删除整个文件夹树到打开的文件。
当前用户没有删除文件/文件夹所需的 (NTFS) 权限的文件/文件夹,这也防止删除此文件/文件夹的文件夹树。
The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:
此命令行使用不删除文件夹的第一个原因删除指定文件夹的所有文件和子文件夹,但不删除文件夹本身。该文件夹临时成为运行命令进程的当前目录,以防止删除文件夹本身。当然,这会导致命令RD输出错误消息:
The process cannot access the file because it is being used by another process.
该进程无法访问该文件,因为它正被另一个进程使用。
Fileis the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directorywhich explains this error message. But I don't want to go too deep into file system management.
File在这里是错误的术语,因为实际上该文件夹正被另一个进程使用,即执行命令RD的当前命令进程。好吧,实际上文件夹是文件系统的一个特殊文件,它具有解释此错误消息的文件属性目录。但我不想太深入地研究文件系统管理。
This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul
from handle STDERRto device NUL.
此错误消息与所有其他错误消息一样,可能由于上述三个原因而发生,通过将其2>nul
从句柄STDERR重定向到设备NUL来抑制。
The third command, POPD, is executed independently of the exit value of command RD.
第三个命令POPD的执行独立于命令RD的退出值。
POPDpops the directory path pushed by PUSHDfrom the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPDdeletes the temporary drive letter created by PUSHDin case of a UNC folder path.
POPD从栈中弹出PUSHD推送的目录路径,将运行命令进程的当前目录改为该目录,即恢复初始当前目录。在 UNC 文件夹路径的情况下,POPD会删除由PUSHD创建的临时驱动器号。
Note:POPDcan silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder%
remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%
.
注意:如果初始当前目录是要清理的目录的子目录而不再存在,则POPD可能会以静默方式无法恢复初始当前目录。在这种特殊情况下%PathToFolder%
仍然是当前目录。因此,建议不要从%PathToFolder%
.
One more interestingfact:I tried the command line also using a UNC path by sharing local directory C:\Temp
with share name Temp
and using UNC path \\%COMPUTERNAME%\Temp\CleanTest
assigned to environment variable PathToFolder
on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1
, Subfolder1
is deleted by RD, and next POPDfails silently in making C:\Temp\CleanTest\Subfolder1
again the current directory resulting in Z:\CleanTest
remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot%
to a local directory really existing. Unfortunately POPDdoes not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.
一个更有趣的事实:我尝试使用 UNC 路径的命令行,方法是在 Windows 7 上共享C:\Temp
具有共享名的本地目录Temp
并使用\\%COMPUTERNAME%\Temp\CleanTest
分配给环境变量的UNC 路径PathToFolder
。如果运行命令行的当前目录是共享本地的子目录使用 UNC 路径访问的文件夹,即C:\Temp\CleanTest\Subfolder1
,Subfolder1
被RD删除,并且下一个POPD无法静默地C:\Temp\CleanTest\Subfolder1
重新创建当前目录,导致Z:\CleanTest
保留为正在运行的命令进程的当前目录。因此,在这种非常非常特殊的情况下,临时驱动器号会一直保留,直到当前目录发生更改,例如cd /D %SystemRoot%
到真正存在的本地目录。不幸的是,如果POPD无法恢复初始当前目录,则它不会以大于 0 的值退出,从而无法仅使用POPD的退出代码来检测这种非常特殊的错误情况。但是,可以假设没有人遇到过这种非常特殊的错误情况,因为 UNC 路径通常不用于访问本地文件和文件夹。
For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.
为了更好地理解所使用的命令,打开一个命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的帮助。
pushd /?
popd /?
rd /?
pushd /?
popd /?
rd /?
Single line with multiple commands using Windows batch fileexplains the operators &&
and &
used here.
使用Windows批处理文件的多个命令一行介绍了经营者&&
和&
用在这里。
Next let us look on the batch file solution using the command DELto delete files in %PathToFolder%
and FORand RDto delete the subfolders in %PathToFolder%
.
接下来,让我们看看在使用该命令的批处理文件解决方案DEL删除的文件%PathToFolder%
和FOR和RD删除子文件夹中%PathToFolder%
。
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"
rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"
rem Consisted the folder path only of double quotes?
if not defined PathToFolder goto EndCleanFolder
rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"
rem Consisted folder path only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder
rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
:EndCleanFolder
endlocal
The batch file first makes sure that environment variable PathToFolder
is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder
is concatenated with other strings during batch file execution.
批处理文件首先确保环境变量PathToFolder
确实是用文件夹路径定义的,没有双引号,末尾没有反斜杠。最后的反斜杠不会有问题,但文件夹路径中的双引号可能会出现问题,因为PathToFolder
在批处理文件执行期间,值与其他字符串连接在一起。
Important are the two lines:
重要的是两行:
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
The command DELis used to delete all files in the specified directory.
DEL命令用于删除指定目录下的所有文件。
- The option
/A
is necessary to process really all files including files with the hidden attribute which DELwould ignore without using option/A
. - The option
/F
is necessary to force deletion of files with the read-only attribute set. - The option
/Q
is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted. >nul
is necessary to redirect the output of the file names written to handle STDOUTto device NULof which can't be deleted because of a file is currently opened or user has no permission to delete the file.2>nul
is necessary to redirect the error message output for each file which can't be deleted from handle STDERRto device NUL.
- 该选项
/A
对于处理真正的所有文件是必要的,包括具有隐藏属性的文件,DEL将在不使用选项的情况下忽略该属性/A
。 - 该选项
/F
是强制删除具有只读属性集的文件所必需的。 - 该选项
/Q
对于运行多个文件的静默删除而不提示用户是否真正删除多个文件是必要的。 >nul
有必要将写入处理STDOUT的文件名的输出重定向到无法删除的设备NUL,因为当前打开了文件或用户没有删除文件的权限。2>nul
必须将无法从句柄STDERR删除的每个文件的错误消息输出重定向到设备NUL。
The commands FORand RDare used to remove all subdirectories in specified directory. But for /D
is not used because of FORis ignoring in this case subdirectories with the hidden attribute set. For that reason for /F
is used to run the following command line in a separate command process started in the background with %ComSpec% /c
:
FOR和RD命令用于删除指定目录下的所有子目录。但是for /D
没有使用,因为在这种情况下FOR忽略了具有隐藏属性集的子目录。因此,for /F
用于在后台启动的单独命令进程中运行以下命令行%ComSpec% /c
:
dir "%PathToFolder%\*" /AD /B 2>nul
DIRoutputs in bare format because of /B
the directory entries with attribute D
, i.e. the names of?all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul
is used to redirect the error message output by DIRon no directory found from handle STDERRto device NUL.
DIR以裸格式输出,因为/B
目录条目具有属性D
,即指定目录中所有子目录的名称独立于其他属性,例如没有路径的隐藏属性。2>nul
用于将DIR在没有从句柄STDERR 中找到的目录上输出的错误消息重定向到设备NUL。
The redirection operator >
must be escaped with the caret character, ^
, on the FORcommand line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FORwhich executes the embedded dir
command line in a separate command process started in the background.
重定向操作符>
必须^
在FOR命令行上使用插入字符 , 进行转义,当 Windows 命令解释器在执行在单独的命令进程中执行嵌入命令行的命令FOR之前处理此命令行时,将被解释为文字字符dir
在后台。
FORprocesses the captured output written to handle STDOUTof a started command process which are the names of the subdirectories without path and never enclosed in double quotes.
FOR处理为处理已启动命令进程的STDOUT而写入的捕获输出,这些输出是没有路径的子目录的名称,并且从不包含在双引号中。
FORwith option /F
ignores empty lines which don't occur here as DIRwith option /B
does not output empty lines.
带有选项的FOR 会/F
忽略此处不会出现的空行,因为带有选项的DIR/B
不会输出空行。
FORwould also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=|
is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.
FOR也会忽略以分号开头的行,分号是默认的行尾字符。目录名可以以分号开头。出于这个原因eol=|
,用于将竖线字符定义为行尾字符,目录或文件的名称中不能包含该字符。
FORwould split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I
. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims=
is used to define an empty list of delimiters to disable the line splitting behavior and get?assigned to the loop variable, I
, always the complete directory name.
FOR将使用空格和水平制表符作为分隔符将行拆分为子字符串,并将仅将第一个空格/制表符分隔的字符串分配给指定的循环变量I
。由于目录名称可以包含一个或多个空格,因此这里不需要这种拆分行为。因此delims=
用于定义一个空的分隔符列表,以禁用行拆分行为并获得分配给循环变量,I
,始终是完整的目录名称。
Command FORruns the command RDfor each directory name without a path which is the reason why on the RDcommand line the folder path must be specified once again which is concatenated with the subfolder name.
命令FOR为每个没有路径的目录名称运行命令RD,这就是为什么在RD命令行上必须再次指定文件夹路径并与子文件夹名称连接的原因。
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
要了解使用的命令及其工作原理,请打开命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?
回答by Filip Gjorgjevikj
Use Notepadto create a text document and copy/paste this:
使用记事本创建一个文本文档并复制/粘贴:
rmdir /s/q "%temp%"
mkdir "%temp%"
Select Save Asand file name:
选择另存为和文件名:
delete_temp.bat
delete_temp.bat
Save as type: All files and click the Savebutton.
保存类型:所有文件,然后单击Save按钮。
It works on any kind of account (administrator or a standard user). Just run it!
它适用于任何类型的帐户(管理员或标准用户)。运行它!
I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!
我在这个例子中使用了一个临时变量,但你可以使用任何其他变量!PS:仅适用于 Windows 操作系统!