Search code examples
batch-filermdir

Run batch file and delete current parent directory


Here is my current set up.

C:\user\Desktop\folder
C:\user\Desktop\folder\run.bat

Because I wasn't able to use rmdir to delete the parent folder I tried making a helper.bat file that was added to the Desktop that would ideally delete the folder and delete itself after running. But I guess the process is still running, so it will only delete the contents of folder but not folder itself?

run.bat:

set HELPERFILE=helper.bat
cd %cd%
cd ..
echo echo Deleting the directory...>%HELPERFILE%
echo pause>>%HELPERFILE%
echo rmdir /s /q testfolder>>%HELPERFILE%
echo del %HELPERFILE%>>%HELPERFILE%
echo pause>>%HELPERFILE%
echo exit>>%HELPERFILE%
call "testing" /wait %HELPERFILE%

How can I delete everything after running run.bat including the parent directory it is contained within? I believe it has something to do with call and/or start?


Solution

  • The trick is to make sure that your batch file is no longer running and that nothing is in a folder being deleted (that is, nothing has a folder to be deleted as the current directory).

    Given a structure

    Z:\
    Z:\Test
    Z:\Test\Kill
    Z:\Test\Kill\run.bat
    

    the following run.bat will completely remove the Kill folder

    REM Do Stuff
    start rmdir Z:\test\kill /s /q
    

    If you run the batch file from a command window, make sure you are not in the Kill folder, e.g.

    Z:\Test> Kill\run.tab