Files
management-scripts/Cleanup-SystemTempFiles.ps1
T
2020-09-17 15:57:43 -04:00

68 lines
2.7 KiB
PowerShell

## 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 )
{
Write-Output "Running with administrative privileges"
## Remove all *.evtx files from $SysTemp
$EventLogs = Get-ChildItem -Path "${SysTemp}\*" -File -Filter *.evtx
If ( $EventLogs )
{
Write-Output "Deleting all event logs from ${SysTemp}"
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 )
{
Write-Output "Deleting misc logs from ${SysTemp}"
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 )
{
Write-Output "Deleting archived CBS logs from ${Env:SystemRoot}\Logs\CBS"
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 )
{
Write-Output "Deleting all temp files not modified in ${OlderThan} day(s) from ${SysTemp}"
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" )
{
Write-Output "Turning off system hibernation"
Try { Start-Process "powercfg" -ArgumentList "-h off" -Wait }
Catch { Write-Output $_.Exception.Message }
}
}
## Only run this section if we don't have administrative privileges
Else
{
Write-Output "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 )
{
Write-Output "Deleting all temp files not modified in ${OlderThan} day(s) from ${Env:TEMP}"
ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile -Force -Recurse -ErrorAction SilentlyContinue }
}
}