servicecli
servicecli

Reputation: 95

How to delete a directory from within that same directory with a batch file?

call :deleteSelf&exit /b
:deleteSelf
start "" /D "C:\Windows" /MIN cmd /c RD /S /Q "C:\Windows\test"&&exit /b

This is the code I use. Batch file running it sits within C:\Windows\test

The file is successfully deleted, along with any other files in the directory, but not the directory itself. Does anyone know some way to solve this issue? I'm rather stumped.

Upvotes: 0

Views: 206

Answers (2)

Frank
Frank

Reputation: 31

surely it's not as easy as adding the following line to your batch file:

cd c:\
rd c:\windows\test

Upvotes: 0

MC ND
MC ND

Reputation: 70923

You will need, at least, to

  • leave the current batch file so it is not open
  • ensure your current active directory is not the one you want to remove

so, if you follow the already pointed dbenham's approach for leaving the current batch file you could use something like

((goto) 2>nul & cd "%~dp0\.." && rmdir /s /q "%~dp0") 

That is,

  • the (goto) will generate an error that will leave current batch file execution
  • we change the current active directory to the parent of the folder where the batch file is stored
  • it the active directory has been changed, we try to remove the folder that holds the batch file

Of course, if there is another process/file locking the folder you will not be able to remove it.

Upvotes: 2

Related Questions