Script Center > Gallery > Storage > Delete Files in Order to Free Up Disk Space
TechNet Script Center logo

Welcome to the TechNet Script Center Gallery!

Each contribution is licensed to you under a License Agreement by its owner, not Microsoft. Microsoft does not guarantee the contribution or purport to grant rights to it.

Delete Files in Order to Free Up Disk Space

(Community)
Rate it:
 
 
 
 
 
Script Code
VBScript
'
' This script will search directory "strDiskToCheck+strDir", and will clean up (delete) files of type "strFileType", 
'   starting with the oldest one, until free disk space on disk "strDiskToCheck" rises above "cnstNeedSpace" bytes.
'
' Useful for cleaning up old backup files to make sure you have space for a new backup.  That's what I use it for, anyway. 
'
' Requires Log Parser 2.2 (http://www.microsoft.com/technet/scriptcenter/resources/tales/sg0105.mspx) to work.
' 
' Note:  Although this script is partially set up to operate on any computer over a network, 
'    it has not been tested on anything but the Local Computer.  In particular, the technique for
'     file deletion would certainly need to be modified.
'
' In order to test this script, make sure you test on a test directory first, and by massaging "cnstNeedSpace" appropriately. 
'
' Note that I formatted this script to most easily be read in Notepad, on a large-ish monitor, with word wrap turned off.
'
' Comments and improvements are welcome and can be e-mailed to ralph@edington.com.  Cheers!
'
'
'
'  These next four constants are the ones you really need to modify for your needs:
'
const strDiskToCheck = "E:"
const strDir = "\backups\backup1\" 
const strFileType = "*.TIB"
const cnstNeedSpace = 120000000000 ' Bytes that we need free, else we're gonna start deleting old files

const GroupDigits = True  ''' Used for formatting numeric output. 
const strComputer = "."   ''' Note: not tested on remote computers yet. Using this because it was in the examples I used.


Wscript.Echo "==================================================================================================" 
Wscript.Echo "This script will delete the oldest " & strFileType & " from directory " & strDiskToCheck & strDir
Wscript.Echo "  until free disk space on " & strDiskToCheck & " rises above " & FormatNumber (cnstNeedSpace, 0, 0, 0, GroupDigits) & " bytes." 
Wscript.Echo " "

'''
''' Spit out the date and time real quick-like. Useful when appending output to a log file:
'''

Set objWMIService = GetObject("winmgmts:"  & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colItems = objWMIService.ExecQuery("Select * from Win32_LocalTime")

For Each objItem in colItems   ''''''' Not sure why we need a loop here.  That's the way the example was written.
    Wscript.Echo "  Current Date & Time is: " & objItem.Month & "/" & objItem.Day & "/" & objItem.Year & "  " & _
                objItem.Hour & ":" & objItem.minute & ":" & objItem.Second
        Wscript.Echo " "
Next


'''
''' Now do an initial check for free disk space:
'''

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DeviceID = '" & strDiskToCheck & "'")

For Each objDisk in colDisks   ''''''' Again, not sure why we need a loop here. We're only checking 1 disk. 
                ''''''''' But that's the way the example was written.
    intFreeSpace = objDisk.FreeSpace
Next

Wscript.Echo "Have free: ", FormatNumber (intFreeSpace, 0, 0, 0, GroupDigits)
Wscript.Echo "Need free: ", FormatNumber (cnstNeedSpace, 0, 0, 0, GroupDigits)


'
' Note: in the following comparisons, the "divide by 1" nonsense seems to be necessary, otherwhile free space 
'     comparisons on large numbers was not working correctly and the answers didn't make sense.  Using "/1" seems 
'    to make these comparisons work.  If you can figure out how to do away with "/1" please let me know.
'

If   cnstNeedSpace/1 > intFreeSpace/1 then
                        Wscript.Echo "Need >  Have.  Better clean up." 
Elseif cnstNeedSpace/1 <= intFreeSpace/1 then
                        Wscript.Echo "Need <= Have.  Don't do anything."
End If


Do Until cnstNeedSpace/1 <= intFreeSpace/1 '''''''''''''''START OF LOOP'''''''''''''''''''''''''''''''''''''''''' 

'''
''' Find the Oldest file in the directory:
'''

    Set objLogParser =     CreateObject("MSUtil.LogQuery")
    Set objInputFormat =     CreateObject("MSUtil.LogQuery.FileSystemInputFormat ")
    objInputFormat.recurse = 0  ''' don't search subdirs, specified directory only.
    objInputFormat.useLocalTime = 1

    strQuery = "SELECT TOP 1 Name, Size, LastWriteTime  FROM '" & strDiskToCheck & strDir & strFileType &"' ORDER BY LastWriteTime ASC" 

''''''    The next 3 lines just produce a listing of the search results in tabular output to the console, 
''''''       don't really need this, as it doesn't help us to get the info into usable variables or anything; 
''''''       but it's useful because it shows the Size of the file being deleted, whereas the next query that returns 
''''''       the data into variables manages to mangle the "Size" of the file into garbage.  Huhn, go figure. 
''''''
    Set objOutputFormat =     CreateObject("MSUtil.LogQuery.NativeOutputFormat")
    objOutputFormat.ralign = 1
    objLogParser.ExecuteBatch strQuery, objInputFormat, objOutputFormat


''''''    Now that the query's all set up, here's where we actually execute the query that's going to put info 
''''''     on the oldest file into variables where the data will be useful:
''''''
    Set objRecordSet = objLogParser.Execute(strQuery, objInputFormat)

    Do While Not objRecordSet.AtEnd
           Set objRecord     = objRecordSet.GetRecord
           strFilename     = objRecord.GetValue("Name")
        intSize     = objRecord.GetValue("Size") 
        ''''     Note that the above assignment returns incorrect "intSize" for large files.  Wasn't able to fix this error.
        ''''    It isn't important for this script, but it's interesting to compare this number to the 
        ''''      tabular results output above.
        dtLastWriteTime = objRecord.GetValue ("LastWriteTime")
           objRecordSet.MoveNext
    Loop    
        ''''''''''  Note: Since we're always only querying for 1 item, i.e. the oldest, 
        ''''''''''  this "loop" will fall through after first and only iteration.
        ''''''''''  Obviously don't really need a loop in this case.  Keeping it as an example for the future, 
        ''''''''''  in case you re-use the same code for a query that does return multiple items...

    '''''  Here's where we actually DELETE THE OLDEST FILE:

    Wscript.echo " "
    Wscript.echo "Deleting oldest file:" &     _
        " Name: "     & strFilename &  _
        ", Size: "     & FormatNumber (intSize, 0, 0, 0, GroupDigits)  & _
        ", ModDate: "     & dtLastWriteTime 
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.DeleteFile(strDiskToCheck & strDir & strFilename)
    Wscript.echo " "


    ''''' Now that we've deleted the oldest file, check the free disk space again: 

    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk Where DeviceID = '" & strDiskToCheck & "'") 
    For Each objDisk in colDisks  ''' AGAIN with the one-iteration "loop"!  Don't need it in this case, only checking 1 disk.
        intFreeSpace = objDisk.FreeSpace
    Next

    Wscript.Echo "Have free: ", FormatNumber (intFreeSpace, 0, 0, 0, GroupDigits) 
    Wscript.Echo "Need free: ", FormatNumber (cnstNeedSpace, 0, 0, 0, GroupDigits)

    '''
    ''' remember the "/1" nonsense is apparently needed !!!!!!!!  See above for more details.
    '''
    If   cnstNeedSpace/1 > intFreeSpace/1 then       
                        Wscript.Echo "Need >  Have.  Better clean up."
    Elseif cnstNeedSpace/1 <= intFreeSpace/1 then    
                         Wscript.Echo "Need <= Have.  Don't do anything. Done."
    End If


Loop ''''''''''''''END OF LOOP''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Platforms
Windows Server 2008 R2 No
Windows Server 2008 No
Windows Server 2003 No
Windows 7 No
Windows Vista No
Windows XP No
Windows 2000 No
For online peer support, join The Official Scripting Guys Forum! To provide feedback or report bugs in sample scripts, please start a new discussion on the Discussions tab for this script.
Disclaimer The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.
Be the first to create a discussion.