Delete directory with exclusion

From NSIS Wiki

Author: BAPBAP (talk, contrib)


Description

These macros allow you to remove all directories except you define.

Provided "as is" by [BAPBAP]. Use on your own risk.

The Script

Function DeleteFoldersWithExclusion
 Exch $R0 ; exclude dir
 Exch
 Exch $R1 ; route dir
 Push $R2
 Push $R3
 
 
  ClearErrors
  FindFirst $R3 $R2 "$R1\*.*"
 
 
  Top:
   StrCmp $R2 "." Next
   StrCmp $R2 ".." Next
   StrCmp $R2 $R0 Exit
   IfFileExists "$R1\$R2\*.*" Jump DeleteFile
 
   Jump:
    Push '$R1\$R2'
    Push '$R0'
    Call DeleteFoldersWithExclusion
 
    Push "$R1\$R2" 
    Call isEmptyDir
    Pop $0    
    StrCmp $0 1 RmD Next
 
   RmD:
    RMDir /r $R1\$R2
    Goto Next
 
   DeleteFile:
    Delete '$R1\$R2'
 
   Next:
    ClearErrors
    FindNext $R3 $R2
    IfErrors Exit
   Goto Top
 
  Exit:
  FindClose $R3
 
 Pop $R3
 Pop $R2
 Pop $R1
 Pop $R0
 
FunctionEnd
 
 
Function isEmptyDir
  # Stack ->                    # Stack: <directory>
  Exch $0                       # Stack: $0
  Push $1                       # Stack: $1, $0
  FindFirst $0 $1 "$0\*.*"
  strcmp $1 "." 0 _notempty
    FindNext $0 $1
    strcmp $1 ".." 0 _notempty
      ClearErrors
      FindNext $0 $1
      IfErrors 0 _notempty
        FindClose $0
        Pop $1                  # Stack: $0
        StrCpy $0 1
        Exch $0                 # Stack: 1 (true)
        goto _end
     _notempty:
       FindClose $0
       Pop $1                   # Stack: $0
       StrCpy $0 0
       Exch $0                  # Stack: 0 (false)
  _end:
FunctionEnd

Usage

Installer code:

  Push "x:\some\dir" 
  Push "settings" 		;dir to exclude
  Call DeleteFoldersWithExclusion
Personal tools
donate