## Source the tools script if it isn't already available If ( !($MSPName) ) { . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) } ## Set the name of the log file $LogName = 'Cleanup-SystemTempFiles' ## Path to the system temp folder $SysTemp = "${Env:SystemRoot}\TEMP" ## When deleting temp files en masse, only delete files/folders older than the number of days specified here $OlderThan = 7 $TimeDelta = New-TimeSpan -Days $OlderThan ## Only run this section if we have administrative privileges If ( IsAdmin ) { Log "Running with administrative privileges" -Name $LogName ## Remove all *.evtx files from $SysTemp $EventLogs = Get-ChildItem -Path "${SysTemp}\*" -File -Filter *.evtx If ( $EventLogs ) { Log "Deleting all event logs from ${SysTemp}" -Name $LogName ForEach ( $EventLog in $EventLogs ) { Remove-Item $EventLog -Force -ErrorAction SilentlyContinue } } ## Remove misc logs and error reports $MiscLogs = Get-ChildItem -Path "${SysTemp}\*" -File -Include "${Env:COMPUTERNAME}-*.log", "AppxErrorReport_*.txt" If ( $MiscLogs ) { Log "Deleting misc logs from ${SysTemp}" -Name $LogName ForEach ( $MiscLog in $MiscLogs ) { Remove-Item $MiscLog -Force -ErrorAction SilentlyContinue } } ## Remove archived CBS logs $CBSLogs = Get-ChildItem -Path "${Env:SystemRoot}\Logs\CBS\*" -File -Include "CbsPersist_*.log", "CbsPersist_*.cab" If ( $CBSLogs ) { Log "Deleting archived CBS logs from ${Env:SystemRoot}\Logs\CBS" -Name $LogName ForEach ( $CBSLog in $CBSLogs ) { Remove-Item $CBSLog -Force -ErrorAction SilentlyContinue } } ## Remove all system temp files older than 7 days $OldTempFiles = Get-ChildItem -Path $SysTemp | Where { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) } If ( $OldTempFiles ) { Log "Deleting all temp files not modified in ${OlderThan} day(s) from ${SysTemp}" -Name $LogName ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile -Force -Recurse -ErrorAction SilentlyContinue } } ## Turn off system hibernation if it's in use If ( Test-Path "${Env:SystemDrive}\hiberfil.sys" ) { Log "Turning off system hibernation" -Name $LogName Try { Start-Process "powercfg" -ArgumentList "-h off" -Wait } Catch { $_.Exception.Message | Log -Error -Name $LogName } } } ## Only run this section if we don't have administrative privileges Else { Log "Running without administrative privileges" ## Remove all system temp files older than 7 days $OldTempFiles = Get-ChildItem -Path $Env:TEMP | Where { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) } If ( $OldTempFiles ) { Log "Deleting all temp files not modified in ${OlderThan} day(s) from ${Env:TEMP}" -Name $LogName ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile -Force -Recurse -ErrorAction SilentlyContinue } } }