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

2019-05-14 11:43发布

Okay, I apologize that I am very new at this, but I am trying to make my batch file delete it's own directory after it has been launched. This is how my folders are arranged:

  • Folder1
    • delete.bat

My goal is to make "delete.bat" delete "Folder1" after "delete.bat" has been launched. So here's my code:

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

This seems like it would work but it only deletes the contents of "Folder1" rather than the whole directory itself. What am I doing wrong?

2条回答
别忘想泡老子
2楼-- · 2019-05-14 12:12

Some thoughts...

  • %~dp0 gets the drive and path of the batch file, so you don't need to include ..\Folder1.
  • What you have should work. If it's not removing the folder itself, it means that it's locked, probably because cmd's current folder is Folder1. (That's a likely guess, but it's not the only reason it might be locked.) If it is cmd, you'll have to call the batch file from another folder, outside of Folder1.
  • While what you have will work, it will result in a funny error when resuming the non-existent batch file: The system cannot find the path specified. You can avoid that in the solution below.

One good solution: start /b "" cmd /c rd /s /q "%~dp0"

This creates a new process to remove the folder (and everything in it, including the batch file itself). Be careful. =)

查看更多
干净又极端
3楼-- · 2019-05-14 12:29

From the corresponding 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.

I guess this is what's going wrong in your case since the batch file is located within the directory that you're trying to delete.

查看更多
登录 后发表回答