VBScript – Delete contents of a folder


To totally unlock this section you need to Log-in


Login

The following simple function, in VBScript, can be called to delete all contents of a folder:

Function DelFol(foldtodel)

Dim FSO, D, F
delfold = foldtodel
Set FSO = CreateObject("Scripting.FileSystemObject")
Set D = FSO.GetFolder(foldtodel)
For Each F In D.Files
FSO.DeleteFile F.path, True
Next
Set FSO = Nothing
End Function

A little modification is to delete all files in all subfolders of a master folder (the parent folder of a directory structure):

Function DelFol(strPath)

Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.getFolder(strPath)
For Each objFile In objFolder.files
objFile.Delete
Next
For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.files
objFile.Delete
Next
Next
for each objSubFolder in objFolder.SubFolders
DelFol(objSubFolder.Path)
next
End Function

Both these functions can be called simply specifying the top folder that we need to purge/clean:

DelFol "C:\Users\user.name\folderTOdelete\"

1 thought on “VBScript – Delete contents of a folder”

Comments are closed.