Monday, January 14, 2008

How to automatically delete unused folders?

Below is a Visual Basic Script that can delete all the sub folders older than 30days from the current date. The folder from which the sub folders need to be deleted can set by  changing the value for strMainFolder variable. This script can also be used to manage files and folder in remote computers just by setting the required computer name/IP to strComputer variable.

The script can be used very effectively by scheduling a job from Windows Task Scheduler.

strComputer = "."
strMainFolder = "C:\"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSubfolders = objWMIService.ExecQuery("Associators of" _
& {Win32_Directory.Name='" & strMainFolder _
& "'} Where AssocClass = Win32_Subdirectory ResultRole = PartComponent")

For Each objFolder in colSubfolders
   dtmFolderCreationDate= CDate(Mid(objFolder.CreationDate,5,2) _
    & "/" & Mid(objFolder.CreationDate, 7, 2) & "/" _
    & Left(objFolder.CreationDate, 4) & " " _
    & Mid (objFolder.CreationDate, 9, 2) & ":" _
    & Mid(objFolder.CreationDate, 11, 2) & ":" _
    & Mid(objFolder.CreationDate,13, 2))
    If (DateDiff("d",dtmFolderCreationDate,Now)>30) Then
    'Wscript.Echo objFolder.Name
    'Wscript.Echo objFolder.CreationDate 
    errResults = objFolder.Delete
    End If
Next

-- Lakshminarasimha Mohan

In God I TRUST everything else I TEST.

No comments: