Script to delete non-locked files and folders

Posted on 2011-05-11
Last Modified: 2012-05-11
Hi experts,

our users have their c:\temp folder cleaned everytime they login. This folder (and/or subfolders) may sometimes contain files that are in-use/locked by the OS. Up until now we used deltree.exe to clean up this folder. The program simply skipped the locked files.
With the introduction of W7 X64, deltree no longer functions. Some googling pointed us to del3.exe as alternative. Unfortunatly, this program exits after the first locked file/folder.

As our login script is VBS based, I'm looking for a procedure that can delete all files and subfolders in any given folder, skipping locked files/folders.

Question by:tdemeyer
    LVL 15

    Accepted Solution

    Here is what I have used.
    On Error Resume Next
    strPath = "C:\Temp"
    Set FSO = CreateObject("Scripting.FileSystemObject")
    CleanSubfolders FSO.GetFolder(strPath)
    wscript.echo "all done"
    Sub CleanSubFolders(Folder)
    	On Error Resume Next
    	For Each Subfolder in Folder.SubFolders
    		CleanSubFolders Subfolder
    End Sub
    Sub DelFiles(Folder)
    	On Error Resume Next
    	set objFolder = FSO.GetFolder(Folder)
    	For Each File in objFolder.Files
    End Sub
    Sub DelFolder(Folder)
    	On Error Resume Next
    	boolCheck = False
    	For Each File in Folder.Files
    		boolCheck = True
    	For Each Subfolder in Folder.Subfolders
    		boolCheck = True
    	If boolCheck = False then
    	End If
    End Sub

    Open in new window


    Author Closing Comment

    Thanks, needed some minor adjustments to fit our own script (due to option explicit), but works flawlessly.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Recently I finished a vbscript that I thought I'd share.  It uses a text file with a list of server names to loop through and get various status reports, then writes them all into an Excel file.  Originally it was put together for our Altiris server…
    I met Paul Devereux (@pdevereux) today when I responded to his tweet asking “Anybody know how to automate adding files from disk to a folder in #outlook  ?”.  I replied back and told Paul that using automation, in this case scripting, to add files t…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now