' ============================================================
' KazTech Safe Temp Cleanup
' Windows 10 / Windows 11
'
' Safely removes temporary files and folders only.
' Locked/in-use files are automatically skipped.
'
' DOES NOT TOUCH:
'   - User documents/downloads
'   - Browser history/cookies/passwords
'   - Recycle Bin
'   - Windows Prefetch
'   - Windows Update cache
'   - Event logs
'   - Registry
'   - Restore points
'   - User/application settings
' ============================================================

Option Explicit

Dim fso, shell, tempPaths, path, expandedPath

Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")

' Safe temporary locations
tempPaths = Array( _
    "%TEMP%", _
    "%TMP%", _
    "%LOCALAPPDATA%\Temp", _
    "%WINDIR%\Temp" _
)

For Each path In tempPaths

    expandedPath = shell.ExpandEnvironmentStrings(path)

    If fso.FolderExists(expandedPath) Then
        CleanFolder expandedPath
    End If

Next

' Completion message
MsgBox "Temporary files cleared.", vbInformation, "KazTech Cleanup"

Set shell = Nothing
Set fso = Nothing

WScript.Quit


' ============================================================
' Delete contents of a folder without deleting the folder itself
' ============================================================

Sub CleanFolder(folderPath)

    Dim folder, file, subFolder

    On Error Resume Next

    Set folder = fso.GetFolder(folderPath)

    If Err.Number <> 0 Then
        Err.Clear
        Exit Sub
    End If

    ' Delete files
    For Each file In folder.Files

        Err.Clear

        ' Remove Read-Only / Hidden / System attributes where possible
        file.Attributes = 0

        Err.Clear
        file.Delete True

        ' Locked/in-use files fail safely and are skipped
        Err.Clear

    Next

    ' Delete subfolders
    For Each subFolder In folder.SubFolders

        Err.Clear

        CleanFolder subFolder.Path

        Err.Clear

        ' Remove folder after its contents have been cleaned
        fso.DeleteFolder subFolder.Path, True

        ' If files are locked, deletion fails safely
        Err.Clear

    Next

    Set folder = Nothing

    On Error GoTo 0

End Sub