Jump to content

System Cleanup Script


Saboath
 Share

Recommended Posts

Im not sure what im missing but this is twice now you have told me to find something in the Tools menu that simply isnt there... I am running SciTE4AutoIt3 and I know its the latest version because I updated a few days ago!

In my tools menu I see the following:

Compile

Build

Go

SyntaxCheck Prod

Stop Executing

Next Message

Previous Message

Clear Output

Switch Pane

Anyway... thanks for that above, I keep forgetting to put the entire path name thinking that the $target will capture all of it!

Also much easier way of adding the size!

Ok, now to the initial problem of the timing.

When I start the app, it opens the main window, I check all the boxes and hit Run.. it tries to run EVERYTHING at once :)

So I need it to do this: if checkbox1 is checked run this function but wait for it to finish, then if checkbox 2 if checked run next function but wait for it to finish, then if checkbox 3 is checked run this function, wait for it to complete, run next function, wait for it to complete etc until it finally gets to the Complete() function which displays the amount of space made available.

Link to comment
Share on other sites

Ok, I have a feeling I only installed the SCiTE part, not the AutoIT part.. will see if I can get that fixed, but heres my code in its entirety (I havnt tested it since moving all the functions to the top):

; This utility turns off system restore, removes all profiles and then runs cleanup.
; Author: Saboath
; Special Thanks: Exodius
; Version: 1.1


#include <GUIConstants.au3>
#include <WindowsConstants.au3>
#Include <Date.au3>
#Include <File.au3>
#include <GuiTab.au3>

Dim $Cleanup, $Help
$totalsize = 0

CleanupGUI()

#Region GUI Layout


; Creates the Main GUI

Func CleanupGUI()
#Region ### START Koda GUI section ### Form=E:\My Documents\My Scripts\guiCleanup.kxf
$guiCleanup = GUICreate("System Cleanup V1.1", 255, 193, -1, -1, BitOR($WS_MINIMIZEBOX,$WS_SYSMENU,$WS_CAPTION,$WS_POPUP,$WS_POPUPWINDOW,$WS_GROUP,$WS_BORDER,$WS_CLIPSIBLINGS,$DS_MODALFRAME))
GUICtrlCreateGroup("", 8, 0, 241, 129)
$chkTurnOffSysRestore = GUICtrlCreateCheckbox("Turn off System Restore", 24, 16, 137, 17)
$chkRemoveProfiles = GUICtrlCreateCheckbox("Remove Profiles Older Than 180 Days", 24, 40, 201, 17)
$chkDiskCleanup = GUICtrlCreateCheckbox("Run Disk Cleanup", 24, 64, 113, 17)
$btnRun = GUICtrlCreateButton("Run", 24, 96, 75, 25)
$btnExit = GUICtrlCreateButton("Exit", 144, 96, 75, 25, 0)
GUICtrlCreateGroup("", -99, -99, 1, 1)
$btnHelp = GUICtrlCreateButton("Help", 96, 144, 57, 17)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###


While 1
$nMsg = GUIGetMsg()
Switch $nMsg

Case $GUI_EVENT_CLOSE
Exit

Case $btnRun
If GUICtrlRead($chkTurnOffSysRestore) = $GUI_CHECKED Then
Sysrestore()
EndIf
If GUICtrlRead($chkRemoveProfiles) = $GUI_CHECKED Then
$answer = MsgBox(4, "Delete Profiles?", "Do You Really Want to Delete All Profiles older than 180 Days?" & @CRLF & @CRLF & "(This is approximately 6 months)")
If $answer = 6 Then
Delprof()
EndIf
EndIf
If GUICtrlRead($chkDiskCleanup) = $GUI_CHECKED Then
DeleteCookies()
DeleteTIP()
DelPref()
DeleteBin()
Complete()
EndIf

Case $btnExit
Exit
Case $btnHelp
HelpGUI()
EndSwitch
WEnd
EndFunc;==>CleanupGUI


; Creates the Help GUI

Func HelpGUI()
GUIDelete($Cleanup)
#include <GUIConstants.au3>

#Region ### START Koda GUI section ### Form=
$Help = GUICreate("Help", 314, 362, 532, 363, BitOR($WS_MINIMIZEBOX,$WS_SYSMENU,$WS_CAPTION,$WS_POPUP,$WS_POPUPWINDOW,$WS_GROUP,$WS_BORDER,$WS_CLIPSIBLINGS,$DS_MODALFRAME))
$Helpgroup = GUICtrlCreateGroup("Cleanup Help", 8, 8, 297, 321)
$Label1 = GUICtrlCreateLabel("This utility performs the following functions:", 16, 32, 204, 17)
$Label2 = GUICtrlCreateLabel("- Turns off System Restore", 40, 56, 129, 17)
$Label3 = GUICtrlCreateLabel("- Removes Profiles Older than 180 Days", 40, 88, 192, 17)
$Label4 = GUICtrlCreateLabel("- Runs a Disk Cleanup.", 40, 120, 113, 17)
$btnOK = GUICtrlCreateButton("OK", 116, 280, 65, 33)
$Label5 = GUICtrlCreateLabel("- Deletes Prefetch Files", 72, 144, 113, 17)
$Label6 = GUICtrlCreateLabel("- Deletes Cookies", 72, 160, 87, 17)
$Label7 = GUICtrlCreateLabel("- Deletes Temporary Internet Files", 72, 176, 162, 17)
$Label8 = GUICtrlCreateLabel("- DeletesTemporary Files (Including index.dat)", 72, 192, 218, 17)
$Label9 = GUICtrlCreateLabel("- Empties Recycle Bins", 72, 208, 112, 17)
$Label10 = GUICtrlCreateLabel("- Gives a total of all space freed up.", 40, 240, 171, 17)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

While 1
$nMsg1 = GUIGetMsg()
Switch $nMsg1
Case $GUI_EVENT_CLOSE
;Exit
GUIDelete($Help)
CleanupGUI()

Case $btnOK()
GUIDelete($Help)
CleanupGUI()
EndSwitch
WEnd
EndFunc;==>HelpGUI

#EndRegion GUI Layout

#Region GUI Functions

;Removes the profiles older than 180 days...
Func Delprof()
_FileCreate("C:\Documents and Settings\All Users\dummyfile.tmp")
$FileList=_FileListToArray("C:\Documents And Settings", "*", 2)
If @Error=1 Then
    MsgBox (0,"","No Files\Folders Found.")
    Exit
EndIf

For $x = 1 to $FileList[0]
    $t = FileGetTime ("C:\Documents And Settings\" & $FileList[$x], 0)
    $varTimeStamp = $t[0] & "/" & $t[1] & "/" & $t[2] & " " & $t[3] & ":" & $t[4] & ":" & $t[5]
    
    $varTimeDifference = _DateDiff ("D", $varTimeStamp, _NowCalc())
;MsgBox (0, "Time Difference", "It's been " & $varTimeDifference & ' days since the profile "' & $FileList[$x] & '" was last accessed.')
    
    If $varTimeDifference >= 180 Then
        $totalsize += DirGetSize("C:\Documents and Settings\" & $FileList[$x])
    DirRemove ("C:\Documents And Settings\" & $FileList[$x], 1)
    EndIf   
Next
EndFunc;==>Delprof

;Turn off System Restore
Func SysRestore()
Run("C:\WINDOWS\system32\rundll32.exe /d C:\WINDOWS\system32\shell32.dll,Control_RunDLL SYSDM.CPL")
WinWait ("System Properties")

$hSysPropWND = WinGetHandle ("System Properties")
$hTabCTRL = ControlGetHandle ($hSysPropWND, "", "SysTabControl321")
_GUICtrlTab_ClickTab ($hTabCTRL, 4)

ControlClick ($hSysPropWND, "", "Button1")

$SysPropText = WinGetText ($hSysPropWND)

$hBtnCTRL = ControlGetHandle ($hSysPropWND, "", "Button5")
ControlClick ($hSysPropWND, "", $hBtnCTRL)

If StringInStr ($SysPropText, "Monitoring") Then
    WinWait ("System Restore")
    $hSysRestWND = WinGetHandle ("System Restore")

    $hBtnCTRL = ControlGetHandle ($hSysRestWND, "", "Button1")
    ControlClick ($hSysRestWND, "", $hBtnCTRL)
    WinWaitClose ($hSysRestWND)
EndIf

WinWaitClose ($hSysPropWND)
EndFunc

; Deletes Cookies
Func DeleteCookies()
    $array = _FileListToArray ("C:\Documents and Settings")
For $x = 1 to $array[0]
    $totalsize += FileGetSize("C:\Documents and Settings\" & $array[$x] & "\Cookies")
    FileDelete ("C:\Documents and Settings\" & $array[$x] & "\Cookies")
Next
EndFunc;==>Deletes Cookies

; Deletes Temporary Internet Files
Func DeleteTIF()
    $array = _FileListToArray ("C:\Documents and Settings")
For $x = 1 to $array[0]
    $totalsize += DirGetSize("C:\Documents and Settings\" & $array[$x] & "\Local Settings\Temporary Internet Files")
    FileDelete ("C:\Documents and Settings\" & $array[$x] & "\Local Settings\Temporary Internet Files")
Next
EndFunc;==>Deletes Temporary Internet Files

; Delete Prefetch Files
Func DelPref()
    $PrefFiles = _FileListToArray (@WindowsDir & "\Prefetch")
For $x = 1 to $PrefFiles[0]
    $totalsize += FileGetSize(@WindowsDir & "\Prefetch\" & $PrefFiles[$x])
    FileDelete (@WindowsDir & "\Prefetch\" & $PrefFiles[$x])
Next
EndFunc;==> Delete Prefetch Files

; Empty Recycle Bins
Func DeleteBin()
    $Bin = _FileListToArray ("C:\RECYCLER")
For $x = 1 to $Bin[0]
    $totalsize += DirGetSize("C:\Recycler\" & $Bin[$x])
    FileRecycleEmpty("C:\")
Next
EndFunc;==>Deletes Recycle Bins

;Recursive File Search
Func RecurseDir($dir, $mask, $dont_recurse=false, $dump="", $return_dirs=false)
;debug(@ScriptLineNumber & ": " & "func: RecurseDir " & $dir)

   Dim $n_dirnames[333333] ; maximum number of directories which can be scanned
   Local $n_dircount = 0   ; ^ could be set much higher, if required
   Local $n_file
   Local $n_search
   Local $n_tfile
   Local $file_array
   Local $filenames
   Local $filecount
   Local $dircount = 1
   Local $msg = "error"

  ; if there was an "\" on the end of the given directory, remove that..
   If StringRight($dir, 1) = "\" then $dir = StringTrimRight($dir, 1)

   $n_dirnames[$dircount] = $dir

   If Not FileExists($dir) Then Return 0

    while $dircount > $n_dircount; keep on looping until all directories are scanned..

        $n_dircount += 1
        $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\*.*")

        While 1 ; find all subdirs in this directory and store them in a array..
            $n_file = FileFindNextFile($n_search) 
            if @error then exitloop
           ; skip directory references..
            if $n_file = "." or $n_file = ".." then continueloop

            $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file

           ; if it's a directory, add it to the list of directories to be processed..
            if StringInStr(FileGetAttrib($n_tfile ), "D") and not $dont_recurse then                                
                $dircount += 1
                $n_dirnames[$dircount] = $n_tfile
            endif
        wend
        FileClose($n_search)

       ; multiple masks..
        if StringInStr($mask, ",", 2) then
            $mask_array = StringSplit($mask, ",")
        else; or else create a dummy array..
            dim $mask_array[2] = [1, $mask]
        endif

       ; loop through the array of masks..
        for $mask_c = 1 to $mask_array[0]
           ; find all files that match this mask..
            $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\" & $mask_array[$mask_c] )  
            if $n_search = -1 then continueloop

            while 1
                $n_file = FileFindNextFile($n_search) 
                if @error then exitloop; end of dir
                if $n_file = "." or $n_file = ".." then continueloop

                $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file
                if not StringInStr(FileGetAttrib( $n_tfile ), "D") then
                    $filecount += 1
                    $filenames &= $n_tfile & @LF
                endif
            wend
            FileClose($n_search)
        next
    wend

   ; flip to a string and back to remove extraneous entries
   ; this is quicker than redimming on every loop
    if $return_dirs then 
        $tmp_str = ""
        $i = 1
        while $n_dirnames[$i] <> ""
            $tmp_str &= $n_dirnames[$i] & "|"
            $i += 1
        wend
        $tmp_str = StringTrimRight($tmp_str, 1)
        $n_dirnames = StringSplit($tmp_str, "|")
        return $n_dirnames
    endif

    $filenames = StringTrimRight($filenames, 1)
    if $filenames = "" then return 0
    $file_array = StringSplit($filenames, @LF)

   ; dump results to a file..
    if $dump then 
        $dump_file = FileOpen($dump, 2)
        FileWrite($dump_file, $filenames)
        FileClose($dump_file)
    endif
    return($file_array)
EndFunc;==> Recursive File Search

; Delete Temporary Files
Func DelTempFiles()
$Delfiles = RecurseDir("C:\", "*.tmp,*.bak,*.chk,index.dat")

For $x = 1 to $DelFiles[0]
    $totalsize += FileGetSize($DelFiles[$x])
    FileDelete($DelFiles)
Next
EndFunc;==> Delete Temporary Files

Func Complete()
    $finalsize = $totalsize / 1048576 
MsgBox(0, "System Cleanup", "The System Cleanup has been completed." & @CRLF & @CRLF & "Please remember to turn off Hibernation in the Power Options" & @CRLF & @CRLF & "Disk Space Acquired: " & Round ($finalsize, 2) & "M")
Exit
EndFunc;==>Complete

#EndRegion GUI Functions
Link to comment
Share on other sites

I guess I have to say I'm a little confused... In what respect is it happening all at once?

I have three things for you at this point...

The first is you should add error checking to protect yourself against array errors. An example of this is:

; Delete Prefetch Files
Func DelPref()
    $PrefFiles = _FileListToArray(@WindowsDir & "\Prefetch")
    If Not @error Then ; If the _FileListToArray failed then we won't try to go through the For...Next loop, it could cause an error
        For $x = 1 To $PrefFiles[0]
            $totalsize += FileGetSize(@WindowsDir & "\Prefetch\" & $PrefFiles[$x])
            FileDelete(@WindowsDir & "\Prefetch\" & $PrefFiles[$x])
        Next
    EndIf
EndFunc   ;==>DelPrefoÝ÷ Ù8^±ç(ج¶¼«ºyââw*'Ê«±Êâ¦Ö§vÇü¨ºX¤z0×âÅë2¢êߢ¹¶Ø§)Òr$Äè¢[:Ù8È­ R¢êÜy8^¶«v)ëz«vËhÊ«rÜz¹í«m)౪Þmªizx§)íê+uêí«r¢íý½ë)yÈçb²Ü(jk¡§!zÍH'"LH(N%³­­§×Eºw­§.)Þ±hZ¶Øb³¥Ú"±§]jX§zX¤zØ^~e£§Ú-çâ®Ëew¨}©e¡ü¨º·îËb¢{,£^Ø^±Êâ¦ÚÞiÈ^²ØZ¶"Ø­ßÙe¸­z­¶ayÊ'²^¶¢Ûh§{^*.®éò¢êìr¸©¶)Òr$ħضËh¶­¦§µ«­¢+Ù
½¹Í½±]É¥Ñ Ìäí ÄÄà¤è ÌäìµÀì5%8µÀìÌäìèÌäìµÀìMµÀìÌä줱Áɽ ¤ÌäìµÀì
H¤ìչѥ½¸QÉoÝ÷ Ûf(¹Ê.ÖtË ^²)ÛzÜz|¨º·îËb¢{,£*.z0}§-¶­Ýý±Æ¥)ඦ¢wµ«bébëaÆ®¶­s`buT7G&Å&VBb33c¶6µGW&äöfe75&W7F÷&RÒb33c´uTô4T4´TBFVà 75&W7F÷&R ×6t&÷ÂgV÷C²gV÷C²Â VæD` buT7G&Å&VBb33c¶6µ&VÖ÷fU&öfÆW2Òb33c´uTô4T4´TBFVà b33c¶ç7vW"Ò×6t&÷BÂgV÷C´FVÆWFR&öfÆW3ògV÷C²ÂgV÷C´Fò÷R&VÆÇvçBFòFVÆWFRÆÂ&öfÆW2öÆFW"F3ògV÷C²fײ5$Äbfײ5$ÄbfײgV÷C²F22&÷ÖFVÇbÖöçF2gV÷C² bb33c¶ç7vW"ÒbFVà FVÇ&öb ×6t&÷ÂgV÷C²gV÷C²Â VæD` VæD` buT7G&Å&VBb33c¶6´F6´6ÆVçWÒb33c´uTô4T4´TBFVà FVÆWFT6öö¶W2 ×6t&÷ÂgV÷C²gV÷C²Â" FVÆWFUD ×6t&÷ÂgV÷C²gV÷C²Â2 FVÅ&Vb ×6t&÷ÂgV÷C²gV÷C²ÂB FVÆWFT&â ×6t&÷ÂgV÷C²gV÷C²ÂR 6ö×ÆWFR VæD
Link to comment
Share on other sites

Alrighty, cleanup made it look nicer and the trace showed they were running one after the other... that was just with the clenaup check box ticked though, I will trial the rest again when I get another PC to clean...

The script ran very quickly and cleaned over 700M in a matter of seconds (much faster than the old cleanup.exe I was running!)

About the only thing I need to worry about now is to add a progress bar to show how the process is going (otherwise it just sits there and looks like nothing is happening...) as I plan to have other people using this I think it would be best to show a progress meter.

Now, I know I need to use the ProgressSet / ProgressOn / ProgressOff sections to do this but the help file I am looking at shows it using time so I need to figure out how to make it work in a count the function progress type way...

Link to comment
Share on other sites

Shouldn't be too hard, do the ProgressOn() as the first thing when you click the $btnRun, then just do the ProgressSet() for whatever % you want to assign as you progress through your functions (and of course put ProgressOff() as the last thing before the Complete() function.

*Edit - Make sure you position your progress bar so it's not over the top of your MessageBoxes! :)

Edited by exodius
Link to comment
Share on other sites

Well, did this one myself! :)

ProgressOn("System Cleanup", "Cleanup is running...", "0 Percent")

DeleteCookies()

ProgressSet(25, "25 Percent", "Cleanup is running...")

DeleteTIF()

ProgressSet(50, "50 Percent", "Cleanup is running...")

DelPref()

ProgressSet(75, "75 Percent", "Cleanup is running...")

DeleteBin()

ProgressSet(100, "100 Percent", "Cleanup is running...")

ProgressOff()

Complete()

Link to comment
Share on other sites

Good work! :)

Would it be worthwhile to mention in either the "maintext" or the "subtext" what it is that you're doing at that step? Like "Deleting Cookies..." "Deleting Temporary Internet Files..."?

*Edit - Oh, and you don't have to say 0 Percent in the initial ProgressOn

*Edit2 - And I see you didn't specify an x or a y pos (see the parameters in the Helpfile), doesn't that center it on top of your messageboxes?

Edited by exodius
Link to comment
Share on other sites

Yeah, amazingly enough I just added that...

Just realised I've ran into a problem with the deletion of the temporary internet files...

Heres the problem in a nutshell... the script currently deletes all files within the 'Temporary Internet Files' directory for each profile, however within this directory is numerous other directories that also contain folders, which may also contain folders etc etc.

I cannot run a DirRemove on it because the 'Temporary Internet Files" is a system folder and the system won't allow it to be deleted.

So as far as I can see, I need to get an array to show a _FileListToArray on the Temporary Internet Files and set the flag to return folders only, I then need to run DirRemove on each of these folders.

Unfortuantely, the function is already running an array to get the usernames and I can't seem to get an array to work within an array but theres probably a way I dont know about.

The function is currently like this:

Func DeleteTIF()
;ConsoleWrite('@@ (183) :(' & @MIN & ':' & @SEC & ') DeleteTIF()' & @CR);### Function Trace
    $array = _FileListToArray("C:\Documents and Settings")
        If Not @error Then
        For $x = 1 To $array[0]
            $totalsize += DirGetSize("C:\Documents and Settings\" & $array[$x] & "\Local Settings\Temporary Internet Files")
            FileDelete("C:\Documents and Settings\" & $array[$x] & "\Local Settings\Temporary Internet Files\")
        Next
    EndIf
EndFunc ;==>DeleteTIF
Edited by Saboath
Link to comment
Share on other sites

Actually, when you call _FileListToArray, it goes off and does it's own thing, then stores what it finds in your variable and you can call it as many times as you want.

Here's the direction you'll want to take this:

#include <File.au3>

DeleteTIF()

Func DeleteTIF()
;ConsoleWrite('@@ (183) :(' & @MIN & ':' & @SEC & ') DeleteTIF()' & @CR);### Function Trace
    $aUsers = _FileListToArray("C:\Documents and Settings", "*", 2)
        If Not @error Then
        For $x = 1 To $aUsers[0]
            $aFolders = _FileListToArray ("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files", "*", 2)
            If Not @error Then
                For $y = 1 to $aFolders[0]
                    MsgBox (0, $aUsers[$x], $aFolders[$y] & @CRLF & DirGetSize("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files\" & $aFolders[$y]) & " bytes")
;~                  $totalsize += DirGetSize("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files\" & $aFolders[$y])
;~                  DirRemove("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files\" & $aFolders[$y], 1)
                Next            
            EndIf
        Next
    EndIf
EndFunc  ;==>DeleteTIF

The CRUCIAL thing to keep track of when you start nesting For...Next loops like this is that you keep your incremental variables (in our case, $x and $y) straight in which array you use them with to reference... Otherwise if you use a $x instead of a $y and $x is bigger than the value of $y can be then you'll crash your script.

Link to comment
Share on other sites

Oh, and if you're ever curious as to what that _FileListToArray does, you can go look at it in your C:\Program Files\AutoIt3\Include\File.au3 file... Just open it in SciTe and do a search for the function name. :)

(The file is read-only, but still, don't change anything in there or you'll probably break some other UDF on yourself down the road.)

Link to comment
Share on other sites

Yeah, the Tidy thing is becoming my new best friend!

Ok, can I declare the $aUser array globally?

Now that the script is basically working I am trying to flesh it out some more (found another folder to delete with temporary files in it [C:\Documents and Settings\Profile\Local Settings\Temp])

So, can I just call the $aUser from the original array or do I need to declare it in each function?

*EDIT*

Global $aUsers, $x ==> ? :)

Edited by Saboath
Link to comment
Share on other sites

Ok, everything is now working!!!! I've had a few of my co-workers test it for me (nice guinnea pigs that they are) and so far 100% success.

Thanks for all your help Exodius!

Good to hear, you should throw up your finished product for the benefit of others looking for such a thing. :)

Link to comment
Share on other sites

Ok, here is the final code for the System Cleanup.

Tested and working successfully.

; This utility turns off system restore, removes all profiles and then runs cleanup.
; Author: Saboath
; Special Thanks: Exodius
; Version: 1.1

#Region;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=Bin.ico
#EndRegion;**** Directives created by AutoIt3Wrapper_GUI ****

#include <GUIConstants.au3>
#include <WindowsConstants.au3>
#include <Date.au3>
#include <File.au3>
#include <GuiTab.au3>

Dim $Cleanup, $Help
Global $aUsers, $x
$totalsize = 0

CleanupGUI()

#Region GUI Layout

; Creates the Main GUI
Func CleanupGUI()
    #Region ### START Koda GUI section ### Form=E:\My Documents\My Scripts\guiCleanup.kxf
    $guiCleanup = GUICreate("System Cleanup V1.1", 255, 193, -1, -1, BitOR($WS_MINIMIZEBOX, $WS_SYSMENU, $WS_CAPTION, $WS_POPUP, $WS_POPUPWINDOW, $WS_GROUP, $WS_BORDER, $WS_CLIPSIBLINGS, $DS_MODALFRAME))
    GUISetIcon("C:\WINDOWS\System32\shell32.dll", -146)
    GUICtrlCreateGroup("", 8, 0, 241, 129)
    $chkTurnOffSysRestore = GUICtrlCreateCheckbox("Turn off System Restore", 24, 16, 137, 17)
    $chkRemoveProfiles = GUICtrlCreateCheckbox("Remove Profiles Older Than 180 Days", 24, 40, 201, 17)
    $chkDiskCleanup = GUICtrlCreateCheckbox("Run Disk Cleanup", 24, 64, 113, 17)
    $btnRun = GUICtrlCreateButton("Run", 24, 96, 75, 25)
    $btnExit = GUICtrlCreateButton("Exit", 144, 96, 75, 25, 0)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $btnHelp = GUICtrlCreateButton("Help", 96, 144, 57, 17)
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###

    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg

            Case $GUI_EVENT_CLOSE
                Exit

            Case $btnRun
                If GUICtrlRead($chkTurnOffSysRestore) = $GUI_CHECKED Then
                    SysRestore()
                EndIf
                If GUICtrlRead($chkRemoveProfiles) = $GUI_CHECKED Then
                    $answer = MsgBox(4, "Delete Profiles?", "Do You Really Want to Delete All Profiles older than 180 Days?" & @CRLF & @CRLF & "(This is approximately 6 months)")
                    If $answer = 6 Then
                        Delprof()
                    EndIf
                EndIf
                If GUICtrlRead($chkDiskCleanup) = $GUI_CHECKED Then
                    ProgressOn("System Cleanup V1.1", "Removing Temp Internet Files", "0 Percent")
                    DeleteTIF()
                    ProgressSet(20, "20 Percent", "Removing Cookies")
                    DeleteCookies()
                    ProgressSet(40, "40 Percent", "Removing Prefetch Files")
                    DelPref()
                    ProgressSet(60, "60 Percent", "Emptying Recycle Bins")
                    DeleteBin()
                    ProgressSet(80, "80 Percent", "Removing Temp Files and Folders")
                    DelTempFiles()
                    DelFoldersTemp()
                    ProgressSet(100, "100 Percent", "Cleanup is Complete!")
                    Sleep(2000)
                    ProgressOff()
                    Complete()
                EndIf

            Case $btnExit
                Exit
            Case $btnHelp
                HelpGUI()
        EndSwitch
    WEnd
EndFunc;==>CleanupGUI

; Creates the Help GUI
Func HelpGUI()
    GUIDelete($Cleanup)
    #include <GUIConstants.au3>

    #Region ### START Koda GUI section ### Form=
    $Help = GUICreate("Help", 314, 362, 532, 363, BitOR($WS_MINIMIZEBOX, $WS_SYSMENU, $WS_CAPTION, $WS_POPUP, $WS_POPUPWINDOW, $WS_GROUP, $WS_BORDER, $WS_CLIPSIBLINGS, $DS_MODALFRAME))
    GUISetIcon("C:\WINDOWS\System32\shell32.dll", -155)
    #NoTrayIcon
    $Helpgroup = GUICtrlCreateGroup("Cleanup Help", 8, 8, 297, 321)
    $Label1 = GUICtrlCreateLabel("This utility performs the following functions:", 16, 32, 204, 17)
    $Label2 = GUICtrlCreateLabel("- Turns off System Restore", 40, 56, 129, 17)
    $Label3 = GUICtrlCreateLabel("- Removes Profiles Older than 180 Days", 40, 88, 192, 17)
    $Label4 = GUICtrlCreateLabel("- Runs a Disk Cleanup.", 40, 120, 113, 17)
    $btnOK = GUICtrlCreateButton("OK", 116, 280, 65, 33)
    $Label5 = GUICtrlCreateLabel("- Deletes Prefetch Files", 72, 144, 113, 17)
    $Label6 = GUICtrlCreateLabel("- Deletes Cookies", 72, 160, 87, 17)
    $Label7 = GUICtrlCreateLabel("- Deletes Temporary Internet Files", 72, 176, 162, 17)
    $Label8 = GUICtrlCreateLabel("- Deletes Temporary Files (Including index.dat)", 72, 192, 218, 17)
    $Label9 = GUICtrlCreateLabel("- Empties Recycle Bins", 72, 208, 112, 17)
    $Label10 = GUICtrlCreateLabel("- Gives a total of all space freed up.", 40, 240, 171, 17)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###

    While 1
        $nMsg1 = GUIGetMsg()
        Switch $nMsg1
            Case $GUI_EVENT_CLOSE
    ;Exit
                GUIDelete($Help)
                CleanupGUI()

            Case $btnOK()
                GUIDelete($Help)
                CleanupGUI()
        EndSwitch
    WEnd
EndFunc;==>HelpGUI

#EndRegion GUI Layout

#Region GUI Functions

; Deletes Temporary Internet Files
Func DeleteTIF()
    $aUsers = _FileListToArray("C:\Documents and Settings")
    If Not @error Then
        For $x = 1 To $aUsers[0]
            $aFolders = _FileListToArray("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files", "*", 2)
            If Not @error Then
                For $y = 1 To $aFolders[0]
                    $totalsize += DirGetSize("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files")
                    DirRemove("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temporary Internet Files\" & $aFolders[$y], 1)
                Next
            EndIf
        Next
    EndIf
EndFunc;==>DeleteTIF

;Removes the profiles older than 180 days...
Func Delprof()
    _FileCreate("C:\Documents and Settings\All Users\dummyfile.tmp")
    $FileList = _FileListToArray("C:\Documents And Settings", "*", 2)
    If @error = 1 Then
        MsgBox(0, "", "No Files\Folders Found.")
        Exit
    EndIf

    For $f = 1 To $FileList[0]
        $t = FileGetTime("C:\Documents And Settings\" & $FileList[$f], 0)
        $varTimeStamp = $t[0] & "/" & $t[1] & "/" & $t[2] & " " & $t[3] & ":" & $t[4] & ":" & $t[5]

        $varTimeDifference = _DateDiff("D", $varTimeStamp, _NowCalc())
;MsgBox (0, "Time Difference", "It's been " & $varTimeDifference & ' days since the profile "' & $FileList[$x] & '" was last accessed.')

        If $varTimeDifference >= 180 Then
            $totalsize += DirGetSize("C:\Documents and Settings\" & $FileList[$f])
            DirRemove("C:\Documents And Settings\" & $FileList[$f], 1)
        EndIf
    Next
EndFunc;==>Delprof

;Turn off System Restore
Func SysRestore()
    Run("C:\WINDOWS\system32\rundll32.exe /d C:\WINDOWS\system32\shell32.dll,Control_RunDLL SYSDM.CPL")
    WinWait("System Properties")

    $hSysPropWND = WinGetHandle("System Properties")
    $hTabCTRL = ControlGetHandle($hSysPropWND, "", "SysTabControl321")
    _GUICtrlTab_ClickTab($hTabCTRL, 4)

    ControlClick($hSysPropWND, "", "Button1")

    $SysPropText = WinGetText($hSysPropWND)

    $hBtnCTRL = ControlGetHandle($hSysPropWND, "", "Button5")
    ControlClick($hSysPropWND, "", $hBtnCTRL)

    If StringInStr($SysPropText, "Monitoring") Then
        WinWait("System Restore")
        $hSysRestWND = WinGetHandle("System Restore")

        $hBtnCTRL = ControlGetHandle($hSysRestWND, "", "Button1")
        ControlClick($hSysRestWND, "", $hBtnCTRL)
        WinWaitClose($hSysRestWND)
    EndIf

    WinWaitClose($hSysPropWND)
EndFunc;==>SysRestore

; Deletes Cookies
Func DeleteCookies()
    $aUsers = _FileListToArray("C:\Documents and Settings")
    If Not @error Then
        For $x = 1 To $aUsers[0]
            $totalsize += DirGetSize("C:\Documents and Settings\" & $aUsers[$x] & "\Cookies")
            FileDelete("C:\Documents and Settings\" & $aUsers[$x] & "\Cookies")
        Next
    EndIf

EndFunc;==>DeleteCookies

; Delete Prefetch Files
Func DelPref()
    $PrefFiles = _FileListToArray(@WindowsDir & "\Prefetch")
    If Not @error Then
        For $p = 1 To $PrefFiles[0]
            $totalsize += FileGetSize(@WindowsDir & "\Prefetch\" & $PrefFiles[$p])
            FileDelete(@WindowsDir & "\Prefetch\" & $PrefFiles[$p])
        Next
    EndIf
EndFunc;==>DelPref

; Empty Recycle Bin
Func DeleteBin()
    $Bin = _FileListToArray("C:\RECYCLER")
    If Not @error Then
        For $b = 1 To $Bin[0]
            $totalsize += DirGetSize("C:\Recycler\" & $Bin[$b])
            FileRecycleEmpty("C:\")
        Next
    EndIf
EndFunc;==>DeleteBin

;Recursive File Search
Func RecurseDir($dir, $mask, $dont_recurse = False, $dump = "", $return_dirs = False)
;debug(@ScriptLineNumber & ": " & "func: RecurseDir " & $dir)

    Dim $n_dirnames[333333]; maximum number of directories which can be scanned
    Local $n_dircount = 0; ^ could be set much higher, if required
    Local $n_file
    Local $n_search
    Local $n_tfile
    Local $file_array
    Local $filenames
    Local $filecount
    Local $dircount = 1
    Local $msg = "error"

; if there was an "\" on the end of the given directory, remove that..
    If StringRight($dir, 1) = "\" Then $dir = StringTrimRight($dir, 1)

    $n_dirnames[$dircount] = $dir

    If Not FileExists($dir) Then Return 0

    While $dircount > $n_dircount; keep on looping until all directories are scanned..

        $n_dircount += 1
        $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\*.*")

        While 1; find all subdirs in this directory and store them in a array..
            $n_file = FileFindNextFile($n_search)
            If @error Then ExitLoop
; skip directory references..
            If $n_file = "." Or $n_file = ".." Then ContinueLoop

            $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file

; if it's a directory, add it to the list of directories to be processed..
            If StringInStr(FileGetAttrib($n_tfile), "D") And Not $dont_recurse Then
                $dircount += 1
                $n_dirnames[$dircount] = $n_tfile
            EndIf
        WEnd
        FileClose($n_search)

; multiple masks..
        If StringInStr($mask, ",", 2) Then
            $mask_array = StringSplit($mask, ",")
        Else; or else create a dummy array..
            Dim $mask_array[2] = [1, $mask]
        EndIf

; loop through the array of masks..
        For $mask_c = 1 To $mask_array[0]
; find all files that match this mask..
            $n_search = FileFindFirstFile($n_dirnames[$n_dircount] & "\" & $mask_array[$mask_c])
            If $n_search = -1 Then ContinueLoop

            While 1
                $n_file = FileFindNextFile($n_search)
                If @error Then ExitLoop; end of dir
                If $n_file = "." Or $n_file = ".." Then ContinueLoop

                $n_tfile = $n_dirnames[$n_dircount] & "\" & $n_file
                If Not StringInStr(FileGetAttrib($n_tfile), "D") Then
                    $filecount += 1
                    $filenames &= $n_tfile & @LF
                EndIf
            WEnd
            FileClose($n_search)
        Next
    WEnd

; flip to a string and back to remove extraneous entries
; this is quicker than redimming on every loop
    If $return_dirs Then
        $tmp_str = ""
        $i = 1
        While $n_dirnames[$i] <> ""
            $tmp_str &= $n_dirnames[$i] & "|"
            $i += 1
        WEnd
        $tmp_str = StringTrimRight($tmp_str, 1)
        $n_dirnames = StringSplit($tmp_str, "|")
        Return $n_dirnames
    EndIf

    $filenames = StringTrimRight($filenames, 1)
    If $filenames = "" Then Return 0
    $file_array = StringSplit($filenames, @LF)

; dump results to a file..
    If $dump Then
        $dump_file = FileOpen($dump, 2)
        FileWrite($dump_file, $filenames)
        FileClose($dump_file)
    EndIf
    Return ($file_array)
EndFunc;==>RecurseDir

; Delete Temporary Files
Func DelTempFiles()
    $Delfiles = RecurseDir("C:\", "*.tmp,*.bak,*.chk,index.dat")
    For $m = 1 To $Delfiles[0]
        $totalsize += FileGetSize($Delfiles[$m])
        FileDelete($Delfiles[$m])
    Next
EndFunc;==>DelTempFiles


Func DelFoldersTemp()
    $aUsers = _FileListToArray("C:\Documents and Settings")
    If Not @error Then
        For $x = 1 To $aUsers[0]
            $totalsize += DirGetSize("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temp")
            DirRemove("C:\Documents and Settings\" & $aUsers[$x] & "\Local Settings\Temp", 1)
            DirRemove("C:\Temp", 1)
        Next
    EndIf
EndFunc;==>DelFoldersTemp

Func Complete()
    $finalsize = $totalsize / 1048576
    MsgBox(0, "System Cleanup", "The System Cleanup has been completed." & @CRLF & @CRLF & "Please remember to turn off Hibernation in the Power Options" & @CRLF & @CRLF & "Disk Space Acquired: " & Round($finalsize, 2) & "M")
    Exit
EndFunc;==>Complete

#EndRegion GUI Functions
Edited by Saboath
Link to comment
Share on other sites

Thanks, great Tool. I didn't exactly wait for something like it, but it comes in handy never the less.

Probably in mid-March I'll try to modify it to also run on remote machines (lookup AD-DC, get comp.account names, etc., pp.). I'll also try to supplement it with functions to control ntbackup.exe (W2K, XP, W2K3) and the "Windows Backup Feature" on W2K8/Vista, respectively. Of course I'll publish my efforts here as well...

Regards,

Chris

Edited by cherdeg
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...