Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for recycle.vbs

(view source code of recycle.vbs as plain text)

  1. Option Explicit
  2.  
  3. Dim arrProtectedRootFolders, arrProtectedSubFolders
  4. Dim blnListOnly, blnQuiet, blnProtected, blnPurgeFolder
  5. Dim intValidArgs, intRC
  6. Dim colItems, objFolder, objFSO, objParentFolder, objProtectedFolder, objProtFolder, objShell, wshShell
  7. Dim strFolder, strProtectedFolderNameSpace, strParentFolder, strTempFolder
  8.  
  9. ' Matt Wilkie's list of shell special folder constants, these folders must NEVER be removed
  10. ' https://gist.github.com/maphew/47e67b6a99e240f01aced8b6b5678eeb
  11. Const ALTSTARTUP       = 29 ' File system directory that corresponds to the user's non-localized Startup program group.
  12. Const APPDATA          = 26 ' Version 4.71. File system directory that serves as a common repository for application-specific data. A typical path is C:\Documents and Settings\username\Application Data.
  13. Const BITBUCKET        = 10 ' Virtual folder that contains the objects in the user's Recycle Bin.
  14. Const COMMONALTSTARTUP = 30 ' File system directory that corresponds to the non-localized Startup program group for all users. Valid only for Windows NT systems.
  15. Const COMMONAPPDATA    = 35 ' Version 5.0. Application data for all users. A typical path is C:\Documents and Settings\All Users\Application Data.
  16. Const COMMONDESKTOPDIR = 25 ' File system directory that contains files and folders that appear on the desktop for all users. A typical path is C:\Documents and Settings\All Users\Desktop. Valid only for Windows NT systems.
  17. Const COMMONFAVORITES  = 31 ' File system directory that serves as a common repository for the favorite URLs shared by all users. Valid only for Windows NT systems.
  18. Const COMMONPROGRAMS   = 23 ' File system directory that contains the directories for the common program groups that appear on the Start menu for all users. A typical path is C:\Documents and Settings\All Users\Start Menu\Programs. Valid only for Windows NT systems.
  19. Const COMMONSTARTMENU  = 22 ' File system directory that contains the programs and folders that appear on the Start menu for all users. A typical path is C:\Documents and Settings\All Users\Start Menu. Valid only for Windows NT systems.
  20. Const COMMONSTARTUP    = 24 ' File system directory that contains the programs that appear in the Startup folder for all users. A typical path is C:\Documents and Settings\All Users\Microsoft\Windows\Start Menu\Programs\StartUp. Valid only for Windows NT systems.
  21. Const CONTROLS         =  3 ' Virtual folder that contains icons for the Control Panel applications.
  22. Const COOKIES          = 33 ' File system directory that serves as a common repository for Internet cookies. A typical path is C:\Documents and Settings\username\Application Data\Microsoft\Windows\Cookies.
  23. Const DESKTOP          =  0 ' Windows desktop: the virtual folder that is the root of the namespace.
  24. Const DESKTOPDIRECTORY = 16 ' File system directory used to physically store the file objects that are displayed on the desktop. It is not to be confused with the desktop folder itself, which is a virtual folder. A typical path is C:\Documents and Settings\username\Desktop.
  25. Const DRIVES           = 17 ' My Computer: the virtual folder that contains everything on the local computer: storage devices, printers, and Control Panel. This folder can also contain mapped network drives.
  26. Const FAVORITES        =  6 ' File system directory that serves as a common repository for the user's favorite URLs. A typical path is C:\Documents and Settings\username\Favorites.
  27. Const FONTS            = 20 ' Virtual folder that contains installed fonts. A typical path is C:\Windows\Fonts.
  28. Const HISTORY          = 34 ' File system directory that serves as a common repository for Internet history items.
  29. Const INTERNETCACHE    = 32 ' File system directory that serves as a common repository for temporary Internet files. A typical path is C:\Users\username\AppData\Local\Microsoft\Windows\Temporary Internet Files.
  30. Const LOCALAPPDATA     = 28 ' Version 5.0. File system directory that serves as a data repository for local (non-roaming) applications. A typical path is C:\Users\username\AppData\Local.
  31. Const MYPICTURES       = 39 ' My Pictures folder. A typical path is C:\Users\username\Pictures.
  32. Const NETHOOD          = 19 ' A file system folder that contains any link objects in the My Network Places virtual folder. It is not the same as ssfNETWORK, which represents the network namespace root. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Network Shortcuts.
  33. Const NETWORK          = 18 ' Network Neighborhood: the virtual folder that represents the root of the network namespace hierarchy.
  34. Const PERSONAL         =  5 ' File system directory that serves as a common repository for a user's documents. A typical path is C:\Users\username\Documents.
  35. Const PRINTERS         =  4 ' Virtual folder that contains installed printers.
  36. Const PRINTHOOD        = 27 ' File system directory that contains any link objects in the Printers virtual folder. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Printer Shortcuts.
  37. Const PROFILE          = 40 ' Version 5.0. User's profile folder.
  38. Const PROGRAMFILES     = 38 ' Version 5.0. Program Files folder. A typical path is C:\Program Files.
  39. Const PROGRAMFILESx86  = 42 ' Version 6.0. Program Files folder. A typical path is C:\Program Files, or C:\Program Files (X86) on a 64-bit computer.
  40. Const PROGRAMS         =  2 ' File system directory that contains the user's program groups (which are also file system directories). A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs.
  41. Const RECENT           =  8 ' File system directory that contains the user's most recently used documents. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Recent.
  42. Const SENDTO           =  9 ' File system directory that contains Send To menu items. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\SendTo.
  43. Const STARTMENU        = 11 ' File system directory that contains Start menu items. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu.
  44. Const STARTUP          =  7 ' File system directory that corresponds to the user's Startup program group. The system starts these programs whenever any user first logs into their profile after a reboot. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\StartUp.
  45. Const SYSTEM           = 37 ' Version 5.0. The System folder. A typical path is C:\Windows\System32.
  46. Const SYSTEMx86        = 41 ' Version 5.0. System folder. A typical path is C:\Windows\System32, or C:\Windows\Syswow32 on a 64-bit computer.
  47. Const TEMPLATES        = 21 ' File system directory that serves as a common repository for document templates.
  48. Const WINDOWS          = 36 ' Version 5.0. Windows directory. This corresponds to the %windir% or %SystemRoot% environment variables. A typical path is C:\Windows.
  49.  
  50. ' Parse command line
  51. intValidArgs = 0
  52. With WScript.Arguments
  53. 	If .Unnamed.Count = 0 Then Syntax ""
  54. 	If .Unnamed.Count > 1 Then Syntax "Invalid command line argument(s)"
  55. 	If .Named.Exists( "?" ) Then Syntax ""
  56. 	blnListOnly   = .Named.Exists( "L" )
  57. 	blnQuiet      = .Named.Exists( "Q" )
  58. 	blnPurgeFolder = .Named.Exists( "P" )
  59. 	If blnListOnly    Then intValidArgs = intValidArgs + 1
  60. 	If blnQuiet       Then intValidArgs = intValidArgs + 1
  61. 	If blnPurgeFolder Then intValidArgs = intValidArgs + 1
  62. 	If .Named.Count <> intValidArgs Then Syntax "Invalid command line switch(es)"
  63. 	' Remove doublequotes and leading or trailing whitespace from specified folder
  64. 	strFolder = Trim( Replace( .Unnamed(0), """", "" ) )
  65. 	' Check for wildcards
  66. 	If InStr( 1, strFolder, "*", vbTextCompare ) Or InStr( 1, strFolder, "?", vbTextCompare ) Then Syntax "Wildcards are not allowed"
  67. End With
  68.  
  69. ' Expand environment variables in specified folder name
  70. Set wshShell = CreateObject("Wscript.Shell")
  71. strFolder = wshShell.ExpandEnvironmentStrings( strFolder )
  72. Set wshShell = Nothing
  73.  
  74. blnProtected = False
  75.  
  76. ' Open the Shell Folders object
  77. Set objShell  = CreateObject( "Shell.Application" )
  78.  
  79. ' Check if a valid folder was specified
  80. Set objFSO = CreateObject( "Scripting.FileSystemObject" )
  81. ' Folder should at least exist
  82. If Not objFSO.FolderExists( strFolder ) Then
  83. 	Syntax "Invalid folder """ & strfolder & """"
  84. End If
  85. ' Get fully qualified path of folder
  86. strFolder = objFSO.GetAbsolutePathName( strFolder )
  87. ' Skip root directories of disk drives
  88. If Len( strFolder ) < 4 Or objFSO.GetParentFolderName( strFolder ) = "" Then
  89. 	Syntax "Removal of root directories is not possible"
  90. End if
  91.  
  92. ' Protect these folders, including their subfolders
  93. arrProtectedSubFolders  = Array( BITBUCKET, CONTROLS, DESKTOP, FONTS, NETHOOD, NETWORK, PRINTERS, PRINTHOOD, PROGRAMFILES, PROGRAMFILESx86, SYSTEM, SYSTEMx86, WINDOWS )
  94. For Each strProtectedFolderNameSpace In arrProtectedSubFolders
  95. 	Set objProtectedFolder = objShell.NameSpace( strProtectedFolderNameSpace )
  96. 	Set objProtFolder      = objProtectedFolder.Self
  97. 	If InStr( 1, strFolder, objProtFolder.Path, vbTextCompare ) Then
  98. 		Syntax "Removal of system folder """ & objProtFolder.Path & """ or its subfolders is prohibited"
  99. 	End If
  100. 	Set objProtFolder      = Nothing
  101. 	Set objProtectedFolder = Nothing
  102. Next
  103.  
  104. ' Protect these folders, but not their content
  105. arrProtectedRootFolders = Array( ALTSTARTUP, APPDATA, COMMONALTSTARTUP, COMMONAPPDATA, COMMONDESKTOPDIR, COMMONFAVORITES, COMMONPROGRAMS, COMMONSTARTMENU, COMMONSTARTUP, COOKIES, DESKTOPDIRECTORY, DRIVES, FAVORITES, HISTORY, INTERNETCACHE, LOCALAPPDATA, MYPICTURES, PERSONAL, PROFILE, PROGRAMS, RECENT, SENDTO, STARTMENU, STARTUP, TEMPLATES )
  106. For Each strProtectedFolderNameSpace In arrProtectedRootFolders
  107. 	Set objProtectedFolder = objShell.NameSpace( strProtectedFolderNameSpace )
  108. 	Set objProtFolder      = objProtectedFolder.Self
  109. 	If LCase( strFolder ) = LCase( objProtFolder.Path ) Then
  110. 		If blnpurgefolder Then
  111. 			blnProtected = True
  112. 		Else
  113. 			Syntax "Removal of system folder """ & strFolder & """ is prohibited"
  114. 		End If
  115. 	End If
  116. 	Set objProtFolder      = Nothing
  117. 	Set objProtectedFolder = Nothing
  118. Next
  119.  
  120. ' Protect TEMP and TMP folders, but not their content
  121. If IsTempFolder( strFolder ) Then
  122. 	If blnPurgeFolder Then
  123. 			blnProtected = True
  124. 	Else
  125. 		Syntax "Removal of temporary folder """ & strFolder & """ is prohibited"
  126. 	End If
  127. End If
  128.  
  129. ' Protect folders listed in the PATH variable, but not their content
  130. If IsInPATH( strFolder ) Then
  131. 	If blnPurgeFolder Then
  132. 			blnProtected = True
  133. 	Else
  134. 		Syntax "Removal of folder """ & strFolder & """ is prohibited because it is listed in the PATH variable"
  135. 	End If
  136. End If
  137.  
  138. ' Set return code to 1 in case no directory was deleted
  139. intRC = 1
  140.  
  141. If blnPurgeFolder And blnProtected Then
  142. 	PurgeFolder strFolder
  143. Else
  144. 	DeleteFolder strFolder
  145. End If
  146.  
  147. ' Clean up
  148. Set objShell        = Nothing
  149. Set colItems        = Nothing
  150. Set objParentFolder = Nothing
  151. Set objFSO          = Nothing
  152.  
  153. ' Return code tells if folder was successfully removed
  154. WScript.Quit intRC
  155.  
  156.  
  157. Sub DeleteFolder( strFolder )
  158. 	' Get parent folder's contents
  159. 	strParentFolder = objFSO.GetParentFolderName( strFolder )
  160. 	Set objParentFolder = objShell.NameSpace( strParentFolder )
  161. 	Set colItems = objParentFolder.Items
  162. 	' Remove specified folder if found in parent folder's content
  163. 	If colItems.Count > 0 Then
  164. 		For Each objFolder In colItems
  165. 			If objFolder.IsFolder And objFolder.Path = strFolder Then
  166. 				If Not blnQuiet    Then WScript.Echo "Moving folder """ & strFolder & """ to the Recycle Bin"
  167. 				If Not blnListOnly Then objFolder.InvokeVerb "Delete"
  168. 				intRC = 0 ' A folder WAS deleted, so return code is set to 0
  169. 			End If
  170. 		Next
  171. 	End If
  172. 	If intRC = 1 And Not blnQuiet Then WScript.Echo "Nothing to delete"
  173. End Sub
  174.  
  175.  
  176. Function IsInPATH( strFolder )
  177. 	Dim arrPATH, blnIsInPATH, i, strPATH, wshShell
  178. 	blnIsInPATH = False
  179. 	Set wshShell = WScript.CreateObject("Wscript.Shell")
  180. 	' Remove doublequotes from PATH and expand environment embedded environment variables
  181. 	With wshShell
  182. 		strPATH = Replace( .ExpandEnvironmentStrings( .Environment.Item( "PATH" ) ), """", "" )
  183. 	End With
  184. 	Set wshShell = Nothing
  185. 	arrPATH = Split( strPATH, ";" )
  186. 	For i = 0 To UBound( arrPATH )
  187. 		If UCase( strFolder ) = UCase( Trim( arrPATH(i) ) ) Then
  188. 			blnIsInPATH = True
  189. 			Exit For
  190. 		End If
  191. 	Next
  192. 	IsInPATH = blnIsInPATH
  193. End Function
  194.  
  195.  
  196. Function IsTempFolder( strFolder )
  197. 	' Find all TEMP and TMP folders for system and all users, and check  the specified folder
  198. 	Dim blnIsTempFolder, colItems, objItem, objWMIService, strTempFolder, wshShell
  199. 	blnIsTempFolder = False
  200. 	Set wshShell       = WScript.CreateObject("Wscript.Shell")
  201. 	Set objWMIService  = GetObject( "winmgmts://./root/CIMV2" )
  202. 	Set colItems       = objWMIService.ExecQuery( "SELECT Name,VariableValue FROM Win32_Environment WHERE Name='TEMP' OR Name='TMP'" )
  203. 	For Each objItem In colItems
  204. 		strTempFolder = wshShell.ExpandEnvironmentStrings( objItem.VariableValue )
  205. 		If UCase( strTempFolder ) = UCase( strFolder ) Then
  206. 			blnIsTempFolder = True
  207. 			Exit For
  208. 		End If
  209. 	Next
  210. 	Set colItems      = Nothing
  211. 	Set objWMIService = Nothing
  212. 	Set wshShell      = Nothing
  213. 	IsTempFolder = blnIsTempFolder
  214. End Function
  215.  
  216.  
  217. Sub PurgeFolder( strFolder )
  218. 	Dim objFolder
  219. 	Dim colItems
  220. 	' Create an object for the specified folder
  221. 	Set objFolder = objShell.Namespace( strFolder )
  222. 	Set colItems  = objFolder.Items
  223. 	' Delete everything in the specified folder
  224. 	If colItems.Count > 0 Then
  225. 	    intRC = 0 ' At least one item in the folder was deleted, so return code is set to 0
  226. 		If Not blnQuiet    Then WScript.Echo "Moving content of folder """ & strFolder & """ to the Recycle Bin"
  227. 	    If Not blnListOnly Then colItems.InvokeVerbEx( "Delete" )
  228. 	Else
  229. 		If Not blnQuiet    Then WScript.Echo "Nothing to delete"
  230. 	End If
  231. 	Set colItems  = Nothing
  232. 	Set objFolder = Nothing
  233. End Sub
  234.  
  235.  
  236. Sub Syntax ( strMsg )
  237. 	If Not Trim( strMsg ) = "" Then
  238. 		strMsg = vbCrLf & "ERROR: " & strMsg & vbCrLf
  239. 	End If
  240. 	strMsg = strMsg _
  241. 	       & vbCrLf _
  242. 	       & "Recycle.vbs,  Version 2.01" _
  243. 	       & vbCrLf _
  244. 	       & "Move a folder and its contents to the Recycle Bin" _
  245. 	       & vbCrLf & vbCrLf _
  246. 	       & "Usage:    " & UCase( WScript.ScriptName ) & "  folder_path  [ options ]" _
  247. 	       & vbCrLf & vbCrLf _
  248. 	       & "Where:    folder_path  specifies the folder to be purged" _
  249. 	       & vbCrLf & vbCrLf _
  250. 	       & "Options:  /L    List selected folder only, do not actually delete" _
  251. 	       & vbCrLf _
  252. 	       & "          /P    Purge files and subfolders in specified protected folder," _
  253. 	       & vbCrLf _
  254. 	       & "                e.g. a temporary folder or root directory" _
  255. 	       & vbCrLf _
  256. 	       & "          /Q    Quiet mode, no screen output (except error messages)" _
  257. 	       & vbCrLf & vbCrLf _
  258. 	       & "Notes:    Several essential folders are protected, and cannot be removed" _
  259. 	       & vbCrLf _
  260. 	       & "          by this script. These include virtual folders (e.g. Desktop)," _
  261. 	       & vbCrLf _
  262. 	       & "          system folders, temporary folders, root directories of disk" _
  263. 	       & vbCrLf _
  264. 	       & "          drives, and all folders listed in the PATH variable. Except" _
  265. 	       & vbCrLf _
  266. 	       & "          for virtual and Windows and Program Files folders, these" _
  267. 	       & vbCrLf _
  268. 	       & "          folders can be purged (command line switch /P), or their" _
  269. 	       & vbCrLf _
  270. 	       & "          subfolders can be deleted (see list of constants for details)." _
  271. 	       & vbCrLf _
  272. 	       & "          Return code will be 0 if the specified folder was deleted" _
  273. 	       & vbCrLf _
  274. 	       & "          (or listed with /L or purged with /P), or 1 otherwise." _
  275. 	       & vbCrLf & vbCrLf _
  276. 	       & "Credits:  List of shell special folder constants by Matt Wilkie" _
  277. 	       & vbCrLf _
  278. 	       & "          https://gist.github.com/maphew/47e67b6a99e240f01aced8b6b5678eeb" _
  279. 	       & vbCrLf & vbCrLf _
  280. 	       & "Written by Rob van der Woude" _
  281. 	       & vbCrLf _
  282. 	       & "https://www.robvanderwoude.com"
  283. 	WScript.Echo strMsg
  284. 	WScript.Quit 1
  285. End Sub
  286.  

page last modified: 2024-04-16; loaded in 0.0119 seconds