如何使批处理文件删除它自己的目录?

How do I make a batch file delete it's own directory?

好的,很抱歉我对此很陌生,但我正试图让我的批处理文件在启动后删除它自己的目录。我的文件夹是这样排列的:

我的目标是在 "delete.bat" 启动后 "delete.bat" 删除 "Folder1"。所以这是我的代码:

rd /s /q %~dp0..\Folder1

这似乎可行,但它只会删除 "Folder1" 的内容,而不是整个目录本身。我做错了什么?

从对应的MSDN link for rd:

You cannot use rmdir to delete the current directory. You must first change to a different directory (not a subdirectory of the current directory) and then use rmdir with a path.

我想这就是您遇到的问题,因为批处理文件位于您要删除的目录中。

一些想法...

  • %~dp0获取批处理文件的驱动器和路径,所以不需要包含..\Folder1.
  • 你所拥有的应该有用。如果它没有删除文件夹本身,则意味着它已被锁定,可能是因为 cmd 的当前文件夹是 Folder1。 (这可能是猜测,但这不是它可能被锁定的唯一原因。)如果是 cmd,则必须从 Folder1 之外的另一个文件夹调用批处理文件。
  • 虽然您拥有的可以工作,但在恢复不存在的批处理文件时会导致一个有趣的错误:系统找不到指定的路径。您可以在下面的解决方案中避免这种情况。

一个好的解决方案:start /b "" cmd /c rd /s /q "%~dp0"

这将创建一个新进程来删除文件夹(以及其中的所有内容,包括批处理文件本身)。当心。 =)

嗯,我认为这是不可能的(至少作为普通用户)

    start /b "" cmd /c rd /s "%~dp0"

删除文件夹,但我认为只有正确的权限

    start /b "" cmd /c rmdir /s "C:/folder"

这有相同的结果

    del /s /q "C:\Temp\folder\*"
    rmdir /s /q "C:\Temp\folder"
    del %0

对于批处理文件,唯一的方法是使用 vbs 脚本或自动热键(发送 !{Space} // 发送 e // 发送 p 公式)或破解它,您只能删除使用的文件和内容由于 cmd 的规范,文件夹但不是工作目录。任何其他语言都不会有问题,因为它在 RAM 内存中。

我推荐这种方式(对于普通用户): 在你的 bat 文件中添加

    copy C:\urpath\deleteafter.bat C:\Temp\deleteafter.bat
    start "" autohotkey.exe "X:\patchto\deletebatchfile.ahk"


    deletebatchfile.ahk
    sleep 2000
    Run, C:\Temp\deleteafter.bat, C:\Temp\
    
    deleteafter.bat
    rmdir /s /q "C:\Temp\batfileworkingpath"
    sleep 3
    del %0

我的实现实际上与 , plus the info from 相同。我添加了 2 秒的延迟,以确保没有时间问题,即使我相信 .bat 文件删除自身时的错误是无害的。

@echo off

:: Do the work
...your command here...

:: In order to delete the current dir we are running from (and all subdirs), none of them can be the
:: current working directory of any running process. Therefore, we are setting our own CWD to something
:: else, so it will be inherited by the below cmd.exe.
cd /d %temp%

:: The countdown is there to allow this batch file to exit, so it can then be deleted safely.
set DelayedSelfDeleteCommand="timeout /t 2 >NUL && rmdir /s /q "%~dp0""

:: Start a separate process (without waiting for it), to execute the command
start "" /b cmd.exe /C %DelayedSelfDeleteCommand%