Clear temp folders on Computer start with PowerShell
16. April 2015
This script will clear the common temp folders on Windows 7 client computers.
$date = Get-Date -Format "dd.mm.yy-HH:mm" $win_temp_folder = "C:\Windows\Temp" $outfile = "C:\tmp\clear_tmp.log" $temp_folders = Get-Item C:\Users\*\AppData\Local\Temp $os = (Get-WMIObject Win32_OperatingSystem).name if ($os -like "*Windows 7*") { # CLEAR APPDATA LOCAL TEMP FOLDER PER USER foreach ($temp_folder in $temp_folders) { $user_temp_files = Get-ChildItem -Path $temp_folder $user_temp_files_count = ($user_temp_files | measure).Count if ($user_temp_files_count -gt 0) { echo "#########################################################################" | Out-File $outfile -Append echo "$date" | Out-File $outfile -Append $user_temp_folder_fullname = $temp_folder.FullName echo "Clearing $user_temp_folder_fullname" | Out-File $outfile -Append Remove-Item $user_temp_folder_fullname\* -Recurse -Force } } # CLEAR WINDOWS TEMP FOLDER echo "Clearing $win_temp_folder" | Out-File $outfile -Append Remove-Item $win_temp_folder\* -Recurse -Force }
In line 4 we make sure to grab the \AppData\Local\Temp folder for every user on the machine and with line 7 we apply this to Windows 7 client PCs only. The script will write it’s activity in the $outfile.
I recommend applying this as a GPO start up script to make sure that none of the files in those folders are in use while the script runs: Computer-Configuration\Policies\Windows-Settings\Scripts\
PowerShell Version: 4
Modules: none