Friday, November 18, 2016

How to Delete a Very Deep Directory Efficiently

In the daily routine of your job, you may have to deal with a directory that has levels very much, that is, the directory is very deep. This situation may often occur to those who use NPM which produces a node_modules directory that has a lot of levels.

Very Deep Directory Structure Image
Very Deep Directory Structure

This directory is the same as the other directories until you realize that actually, this directory requires special treatment to remove, especially on Windows operating systems. This directory cannot be removed immediately. You must remove the sub-directory at a certain level before you delete the directory. This is very inefficient and can slow down your performance.

Fortunately, Windows already has the tool you need, robocopy. In short,  robocopy is a directory and/or file replication command. To use robocopy for deleting very deep directory structure, We use an option called PURGE. The PURGE option deletes destination files and directories that no longer exist in the source. Follow these steps:

  1. Open Command Prompt and CD to the parent of the target directory. For example, if the directory you want to delete is C:\Archive\deep_directory, then CD to C:\Archive
  2. Run command mkdir empty_directory to create an empty directory called empty_directory
  3. Run robocopy .\empty_directory .\deep_directory /purge
  4. Run rmdir empty_directory to remove the unused empty directory and the target directory
Now your deep directory should be gone. This method is not efficient, especially if you need to do it repeatedly. We can automate these steps by writing a BAT file:

ECHO Directory successfully removed

Save those commands into rmdir_deep.bat and put it into one of your directories in PATH system/user variable. You can run the command rmdir_deep <target_directory> from Command Prompt.

No comments:

Post a Comment