You are not logged in.

#1 04 Dec 2015 08:05

Eehixohw
Member
Registered: 25 Sep 2011
Posts: 40

Script to remove itself and it's parent folder

Say that we have a folder A with multiple subfolders and some files. I would like two variants of a script where one would delete itself and its parent folder and other script where it will delete itself and all files in the same folder but leave the parent folder.

Expected behaviour:

A\test.cmd
A\arc1
A\arc2\arcnote.txt

Delete the folder A completely after test.cmd execution



Desktop\test.cmd
Desktop\arc1
Desktop\arc2\arcnote.txt

Delete all files on current location (desktop) after test.cmd execution



The code I've found and adjusted is the for removing files from the same location but it is not working:

for %i in (*) do if not %i == %~n0.cmd del %i
(goto) 2>nul & del "%~f0"

Thank you

Last edited by Eehixohw (04 Dec 2015 09:04)

Offline

#2 04 Dec 2015 09:11

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Script to remove itself and it's parent folder

Delete everything including parent:

cd /d "%~d0\"
start "Deleting %~dp0" cmd /c ping 127.1 -n 3 >nul ^& rmdir /s /q "%~dp0"

Delete everything except parent:

cd /d "%~dp0"
start "Deleting %~dp0\*" cmd /c ping 127.1 -n 3 >nul ^& rmdir /s /q "%~dp0" 2^>nul

These work by spawning a new cmd thread which waits a moment and then deletes the requested directory, recursively.  You should put these lines as the very last thing your script does (deleting a running script may have unpredictable results).

In the first one, I'm making sure the spawn cmd thread is NOT running in the directory you want to delete, so that it can be removed.
The second one takes advantage of how cmd works -- you can't delete a directory that is the working directory of an active cmd session.  In this case I make sure the spawned thread is working in the script location, thus the contents is removed but not the parent.

Last edited by bluesxman (04 Dec 2015 10:42)


cmd | *sh | ruby | chef

Offline

#3 04 Dec 2015 10:09

Eehixohw
Member
Registered: 25 Sep 2011
Posts: 40

Re: Script to remove itself and it's parent folder

Could you explain when should we use pushd %~dp0 and when cd /d %~dp0 ? I know that pushd creates a temporary drive letter if run from network but are they different somehow? We could use them interchangeably, right?

Thank you so much for the help.

Offline

#4 04 Dec 2015 10:56

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Script to remove itself and it's parent folder

The net effect of "pushd" and "cd /d" is broadly the same -- cd's lack of support for "UNC paths" is probably the only difference of significance.  There might be a small overhead in the stack stored for "popd" usage, but from a quick test I'm not seeing any particular issues.  I ran 20000 pushd then followed this with 20000 popd and wound up back in the correct starting place.


cmd | *sh | ruby | chef

Offline

Board footer

Powered by