Jump to content

Delete non used files from %temp%


Recommended Posts

So i have been searching for a while now, and can't find a topic that can help with my problem.

In advance i will apologizes for my English, gramma and bad commas and periods.

So i wanna make a script that defrag the pc, delete folders from the %temp% folder ( C:\Users\"username"\AppData\Local\Temp ) but all the different ways i try just fail.

i have tried with #RequireAdmin and still nothing will work.

Script to empty the temp folder:

#Region Empty Tempt Folder
Local Const $sFilePath = (@TempDir & "\*")
ConsoleWrite($sFilePath)
if Not IsAdmin Then
   ConsoleWrite("NO ADMIN!")
Else
FileDelete ($sFilePath)

EndIf
#EndRegion

 

After a couple of days testing different ways, i'm lost now, so i would hope that someone could help me. In advance i will say Thanks :)

Full Script:

#RequireAdmin
#Region Inclueds
#include <WinAPIFiles.au3>
#EndRegion
#Region Defrag
run ("dfrgui.exe")
WinWaitActive ("dfrgui","",5)
ControlClick("Disk Defragmenter","","[CLASS:Button; INSTANCE:3]")

sleep (5000)
ConsoleWrite("sleep is over")
WinActivate("dfrgui")

While 1
If ControlCommand("Disk Defragmenter", "Analyze disk", "[CLASS:Button; INSTANCE:2]", "IsEnabled", "") Then ExitLoop
    Sleep(100) ; Important or you eat all the CPU which will not help the defrag!
WEnd

ConsoleWrite(@LF & "Defrag Done")
sleep (1000)
ProcessClose("dfrgui.exe")
#EndRegion
#Region Empty Tempt Folder
Local Const $sFilePath = (@TempDir & "\*")
ConsoleWrite($sFilePath)
if Not IsAdmin Then
   ConsoleWrite("NO ADMIN!")
Else
FileDelete ($sFilePath)

EndIf
#EndRegion

 

Link to comment
Share on other sites

  • Moderators

@donpot if you do a search of the forum you will find a number of system cleanup type scripts. This is one that I used to use to prepare a machine for cloning, although I have not updated in quite some time. It may give you some ideas:

#RequireAdmin

#include <Array.au3>
#include <EventLog.au3>
#include <File.au3>

;======================
;Enable Defrag Service
;Perform Cleanup Operations
;Disable Defrag Service (company policy)
;=====================

_defragSVC(2)
_diskCleanup()
_diskDrafrag()
_clearEvents()
_defragSVC(1)
Sleep(1000)
_deleteTempFiles()
_shutDown()

Func _diskCleanup()
    $sMainKey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\"

    Local $aSubKeys[21]
        $aSubKeys[0] = "Active Setup Temp Folders"
        $aSubKeys[1] = "Debug Dump Files"
        $aSubKeys[2] = "Downloaded Program Files"
        $aSubKeys[3] = "Internet Cache Files"
        $aSubKeys[4] = "Memory Dump Files"
        $aSubKeys[5] = "Offline Pages Files"
        $aSubKeys[6] = "Old ChkDsk Files"
        $aSubKeys[7] = "Previous Installations"
        $aSubKeys[8] = "Recycle Bin"
        $aSubKeys[9] = "Setup Log Files"
        $aSubKeys[10] = "System error memory dump files"
        $aSubKeys[11] = "System $error minidump files"
        $aSubKeys[12] = "Temporary Files"
        $aSubKeys[13] = "Temporary Setup Files"
        $aSubKeys[14] = "Thumbnail Cache"
        $aSubKeys[15] = "Update Cleanup"
        $aSubKeys[16] = "Upgrade Discarded Files"
        $aSubKeys[17] = "Windows Error Reporting Archive Files"
        $aSubKeys[18] = "Windows Error Reporting Queue Files"
        $aSubKeys[19] = "Windows Error Reporting System Archive Files"
        $aSubKeys[20] = "Windows Error Reporting System Queue Files"


    For $sKey In $aSubKeys
        RegWrite($sMainKey & $sKey, "StateFlags0666", "REG_DWORD", 2)
    Next

        $sDiskSize = Round((DriveSpaceTotal("C:") / 1024), 2)
        $sDiskFree = DriveSpaceFree("C:")
        ShellExecuteWait("cleanmgr.exe", "/sagerun:666")
        Sleep(500)
        $sNewDiskFree = DriveSpaceFree("C:")

    For $sKey In $aSubKeys
        RegDelete($sMainKey & $sKey, "StateFlags0666")
    Next
EndFunc

Func _diskDrafrag()
    If @OSArch = "X64" Then
        _Wow64FsRedirection(False)
        Sleep(1000)
    EndIf

    Local $aArray = DriveGetDrive("ALL")
        For $i = 1 To $aArray[0]
            If DriveGetType($aArray[$i]) = "Fixed" Then
                Run(@ComSpec & " /k defrag " & $aArray[$i] & " /H /U /V", @SystemDir, @SW_MAXIMIZE)
                    Sleep(2000)
                    While ProcessExists("Defrag.exe")
                        Sleep(100)
                    WEnd
                WinClose("[CLASS:ConsoleWindowClass]", "")
                Sleep(500)

                Run(@ComSpec & " /k defrag " & $aArray[$i] & " /H /U /V /X", @SystemDir, @SW_MAXIMIZE)
                    Sleep(2000)
                    While ProcessExists("Defrag.exe")
                        Sleep(100)
                    WEnd
                WinClose("[CLASS:ConsoleWindowClass]", "")
                Sleep(500)
            EndIf
        Next
    If @OSArch = "X64" Then _Wow64FsRedirection(True)
EndFunc

Func _clearEvents()
    $sTime = TimerInit()
    RunWait(@ComSpec & " /c wevtutil el > C:\Temp\logs.txt", @SystemDir, @SW_HIDE)
    Local $aLogs, $hEventLog, $file = "C:\Temp\Logs.txt"
        _FileReadToArray($file, $aLogs)
        _ArraySort($aLogs)

    For $i = 0 To UBound($aLogs) - 1
        $hEventLog = _EventLog__Open("", $aLogs[$i])
        _EventLog__Clear($hEventLog, "")
        _EventLog__Close($hEventLog)
    Next

    $hEventLog = _EventLog__Open("", "System")
    _EventLog__Clear($hEventLog, "")
    _EventLog__Close($hEventLog)

    Sleep(1000)
    FileDelete($file)
EndFunc

Func _deleteTempFiles()
    $aFolders = _FileListToArray(@TempDir, "*", $FLTA_FOLDERS, True)
    $aFiles = _FileListToArray(@TempDir, "*", $FLTA_FILES, True)


    If IsArray($aFolders) Then
        For $i = 1 To $aFolders[0]
            DirRemove($aFolders[$i], 1)
        Next
    EndIf

    If IsArray($aFiles) Then
        For $x = 1 To $aFiles[0]
            If Not StringInStr($aFiles[$x], "FXSAPI") Then FileDelete($aFiles[$x])
        Next
    EndIf
EndFunc

Func _shutDown()
    $complete = MsgBox(1, "Disk Maintenance", "Maintenance complete, system will shut down in 10 seconds.")
        If $complete = 2 Then
            Exit
        Else
            $oWMI = ObjGet("winmgmts:\\" & @ComputerName & "\root\cimv2")
            $oDHCPNic = $oWMI.ExecQuery("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
                For $oNIC In $oDHCPNic
                    $oNIC.ReleaseDHCPLease()
                Next

            Shutdown(12)
        EndIf
EndFunc

Func _Wow64FsRedirection($state)
    If @OSArch = "X64" Then
        If $state Then
            DllCall("kernel32.dll", "int", "Wow64RevertWow64FsRedirection", "int", 0)
        Else
            DllCall("kernel32.dll", "int", "Wow64DisableWow64FsRedirection", "int", 0)
        EndIf
        If @error Then Return SetError(1)
    EndIf
EndFunc

Func _defragSVC($iState)
    $oServices = ObjGet("winmgmts:\\.\Root\CIMv2").ExecQuery("SELECT * FROM Win32_Service WHERE Name = 'defragsvc'")
        If IsObj($oServices) Then
            If $iState = 1 Then
                For $sService In $oServices
                    $sService.StopService()
                    $sService.ChangeStartMode("Disabled")
                Next
            ElseIf $iState = 2 Then
                For $sService In $oServices
                    $sService.ChangeStartMode("Manual")
                    Sleep(500)
                    $sService.StartService()
                Next
            EndIf
        EndIf
EndFunc

 

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

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...