'==============================================================
'It is recommended to test the script on a local machine for its purpose and effects.
'ManageEngine Endpoint Central will not be responsible for any
'damage/loss to the data/setup based on the behavior of the script.
'Description        - System Level Cleanup
'                     Windows Update Cache, System Temp, Memory Dumps,
'                     Windows Error Reporting, SCCM Cache,WinSxS
'Configuration Type - COMPUTER
'==============================================================

On Error Resume Next

Dim fso, WshShell
Set fso      = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")


' WINDOWS UPDATE CACHE cleanup
Const WU_PATH = "C:\Windows\SoftwareDistribution\Download"

If fso.FolderExists(WU_PATH) Then
    Call WU_CleanFolder(fso.GetFolder(WU_PATH))
    WScript.Echo "Windows Update Cache Cleanup Completed."
Else
    WScript.Echo "Windows Update Cache folder not found."
End If

Sub WU_CleanFolder(folder)
    Dim f, sf
    For Each f In folder.Files
        If PathIsUnder(f.Path, WU_PATH) Then   
            fso.DeleteFile f.Path, True
        End If
    Next
    For Each sf In folder.SubFolders
        If PathIsUnder(sf.Path, WU_PATH) Then  
            Call WU_RemoveSubFolder(sf)
        End If
    Next
End Sub
Sub WU_RemoveSubFolder(folder)
    Dim f, sf
    For Each f In folder.Files
        If PathIsUnder(f.Path, WU_PATH) Then
            fso.DeleteFile f.Path, True
        End If
    Next
    For Each sf In folder.SubFolders
        If PathIsUnder(sf.Path, WU_PATH) Then
            Call WU_RemoveSubFolder(sf)
        End If
    Next
    If PathIsUnder(folder.Path, WU_PATH) Then
        fso.DeleteFolder folder.Path, True
    End If
End Sub


' WINDOWS SYSTEM TEMP cleanup
Const TEMP_PATH = "C:\Windows\Temp"
If fso.FolderExists(TEMP_PATH) Then
    Call TEMP_CleanFolder(fso.GetFolder(TEMP_PATH))
    WScript.Echo "Windows System Temp Cleanup Completed."
Else
    WScript.Echo "Windows Systen Temp folder not found."
End If

Sub TEMP_CleanFolder(folder)
    Dim f, sf, d
    For Each f In folder.Files
    	If PathIsUnder(f.Path, TEMP_PATH) Then 
		d = DateDiff("d", f.DateLastModified, Now)
		If d >= 0 And d > 7 Then    
		    fso.DeleteFile f.Path, True
		End If
	End If
    Next
    For Each sf In folder.SubFolders
        If PathIsUnder(sf.Path, TEMP_PATH) Then
            Call TEMP_CleanSubFolder(sf)
        End If
    Next
End Sub

Sub TEMP_CleanSubFolder(folder)
    Dim f, sf, refreshed, d
    For Each f In folder.Files
        If PathIsUnder(f.Path, TEMP_PATH) Then
            d = DateDiff("d", f.DateLastModified, Now)
            If d >= 0 And d > 7 Then
                fso.DeleteFile f.Path, True
            End If
        End If
    Next
    For Each sf In folder.SubFolders
        If PathIsUnder(sf.Path, TEMP_PATH) Then
            Call TEMP_CleanSubFolder(sf)
        End If
    Next
    Set refreshed = fso.GetFolder(folder.Path)
    If refreshed.Files.Count = 0 And refreshed.SubFolders.Count = 0 Then
        fso.DeleteFolder refreshed.Path, True
    End If
End Sub


' MEMORY DUMP FILES cleanup 
Const MINIDUMP_PATH = "C:\Windows\Minidump"
Dim dumpFile, miniFile, age
If fso.FileExists("C:\Windows\MEMORY.DMP") Then
    Set dumpFile = fso.GetFile("C:\Windows\MEMORY.DMP")
    age = DateDiff("d", dumpFile.DateLastModified, Now)
    If age >= 0 And age > 30 Then
        fso.DeleteFile dumpFile.Path, True
        WScript.Echo "MEMORY.DMP deleted."
    Else
        WScript.Echo "MEMORY.DMP is recent (< 30 days) - skipped."
    End If
Else
    WScript.Echo "MEMORY.DMP not found."
End If

If fso.FolderExists(MINIDUMP_PATH) Then
    For Each miniFile In fso.GetFolder(MINIDUMP_PATH).Files
        If PathIsUnder(miniFile.Path, MINIDUMP_PATH) Then 
              age = DateDiff("d", miniFile.DateLastModified, Now)
              If age >= 0 And age > 30 Then
                   fso.DeleteFile miniFile.Path, True
              End If
        End If
    Next
    If fso.GetFolder("C:\Windows\Minidump").Files.Count = 0 Then
    End If
    WScript.Echo "Minidump Cleanup Completed."
Else
    WScript.Echo "Minidump folder not found."
End If


' WINDOWS ERROR REPORTING (WER)
Const WER_PATH  = "C:\ProgramData\Microsoft\Windows\WER"
If fso.FolderExists(WER_PATH) Then
    Call WER_CleanFolder(fso.GetFolder(WER_PATH), True)
    WScript.Echo "WER Cleanup Completed."
Else
    WScript.Echo "WER folder not found."
End If

Sub WER_CleanFolder(folder, isRootFolder)
    Dim f, sf, age
    For Each f In folder.Files
    	If PathIsUnder(f.Path, WER_PATH) Then
	    age = DateDiff("d", f.DateLastModified, Now)
            If age >= 0 And age > 30 Then
                fso.DeleteFile f.Path, True
            End If
	End If
    Next
    For Each sf In folder.SubFolders
        If PathIsUnder(sf.Path, WER_PATH) Then
	    Call WER_CleanFolder(sf,False)
	End If
    Next
    ' remove empty folders
    If Not isRootFolder Then
        If folder.Files.Count = 0 And folder.SubFolders.Count = 0 Then
            fso.DeleteFolder folder.Path, True
        End If
    End If
End Sub

' SCCM CLIENT CACHE cleanup
Const SCCM_ROOT = "C:\Windows\ccmcache"
Const AGE_DAYS  = 30

' official SCCM method — UIResource.UIResourceMgr API
Dim apiSuccess : apiSuccess = False
Dim oUIResManager, oCache, oCacheElements, oCacheElement

Set oUIResManager = CreateObject("UIResource.UIResourceMgr")
If Not (oUIResManager Is Nothing) Then
    Set oCache = oUIResManager.GetCacheInfo()
    If Not (oCache Is Nothing) Then
        Set oCacheElements = oCache.GetCacheElements()
        If Not (oCacheElements Is Nothing) Then
            For Each oCacheElement In oCacheElements
                Call oCache.DeleteCacheElement(oCacheElement.CacheElementID)
            Next
            apiSuccess = True
            WScript.Echo "SCCM Cache Cleanup Completed via UIResource API."
        End If
    End If
End If
Set oCacheElements = Nothing
Set oCache         = Nothing
Set oUIResManager  = Nothing

' FALLBACK 
If Not apiSuccess Then
    If fso.FolderExists(SCCM_ROOT) Then
        Dim sccmSf, folderAge
        For Each sccmSf In fso.GetFolder(SCCM_ROOT).SubFolders
            If PathIsUnder(sccmSf.Path, SCCM_ROOT) Then
                folderAge = DateDiff("d", sccmSf.DateLastModified, Now)
                If folderAge >= 0 And folderAge > AGE_DAYS Then
                    fso.DeleteFolder sccmSf.Path, True
                End If
            End If
        Next
        WScript.Echo "SCCM Cache Cleanup Completed via folder scan."
    Else
        WScript.Echo "SCCM Cache folder not found (No SCCM managed machine)."
    End If
End If

' UTILITY FUNCTION
Function PathIsUnder(childPath, parentPath)
    Dim parent : parent = LCase(parentPath)
    Dim child  : child  = LCase(childPath)
    If Right(parent, 1) <> "\" Then parent = parent & "\"
    PathIsUnder = (Left(child, Len(parent)) = parent)
End Function

' WinSxS COMPONENT STORE CLEANUP
' Note: Fully updated systems complete cleanup immediately; pending updates may require reboot before Using this Script for Complete cleanup.
Dim dismCmd, rc
dismCmd = "DISM.exe /Online /Cleanup-Image /StartComponentCleanup /NoRestart"
rc = WshShell.Run(dismCmd, 0, True)
Select Case rc
    Case 0
        WScript.Echo "WinSxS Component Cleanup Completed Successfully."
    Case 3010
        WScript.Echo "Cleanup Completed. Reboot Required."
    Case 740
        WScript.Echo "DISM Failed: Elevation Required.(Adminisitrator Access Needed)"
    Case Else
        WScript.Echo "DISM Failed. Exit Code: " & rc
End Select
WScript.Echo "WinSxS Cleanup Completed."

WScript.Echo "System Level Cleanup Completed."
