How would I go about creating a task to delete .bak files on my server?
How would I go about creating a task to delete .bak files on my server?
Here is a combination of code I wrote and ripped off that you can try.
Set the Constant strTopLevelDir to the top level of your server
The Const strFilter will filter out .bak, but you can filter other types
You might have to set attributes of the files to eliminate the read only flags if present.
Sub main()
Const strTopLevelDir = "V:\Vault\"
Const strFilter = "*.bak"
Set fso = CreateObject("Scripting.FileSystemObject")
Dim colAllFiles As Collection
Set colAllFiles = ListFiles(strTopLevelDir, strFilter, True)
For Each f In colAllFiles
Debug.Print f 'For Debugging only
'fso.DeleteFile(f)
Next f
End Sub
Sub GetListOfFilesWithFilter()
Dim colFiles As New Collection
strFilter = "C:\*.*"
strReturn = Dir(strFilter, vbHidden + vbNormal)
While strReturn <> ""
colFiles.Add (strReturn)
strReturn = Dir
Wend
For Each f In colFiles
Debug.Print f
Next f
End Sub
Function ListFiles(strPath As String, Optional strFileSpec As String, _
Optional bIncludeSubfolders As Boolean) As Collection
On Error GoTo Err_Handler
Dim colDirList As New Collection
Dim varItem As Variant
Call FillDir(colDirList, strPath, strFileSpec, bIncludeSubfolders)
Set ListFiles = colDirList
Exit_Handler:
Exit Function
Err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume Exit_Handler
End Function
Private Function FillDir(colDirList As Collection, ByVal strFolder As String, strFileSpec As String, _
bIncludeSubfolders As Boolean)
'Build up a list of files, and then add add to this list, any additional folders
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
'Add the files to the folder.
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colDirList.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Build collection of additional subfolders.
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0& Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call function recursively for each subfolder.
For Each vFolderName In colFolders
Call FillDir(colDirList, strFolder & TrailingSlash(vFolderName), strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(varIn As Variant) As String
If Len(varIn) > 0& Then
If Right(varIn, 1&) = "\" Then
TrailingSlash = varIn
Else
TrailingSlash = varIn & "\"
End If
End If
End Function
Batch file?