Clear the Cache and Temp Files in User Profiles on Windows (RDS) with PowerShell and GPO Ranjan.info

Windows Server RDS farm administrators often face the problem of running out of space on the system drive due to the large amount of user data. This article shows you how to use PowerShell and Group Policies to automatically clean up the Recycle Bin, Downloads, Temp, and Cache folders in user profiles on Windows.

Automatically cleanup temp and download folders with Windows Storage Spaces

you can use the built-in storage sense Automatic removal of old and temporary files on Windows Server 2019/2022 and Windows 10/11. It has special GPO options that allow you to clean up the Temp and Downloads folders.

Storage Spaces - Delete Temporary Files

How to Empty the Recycle Bin for Windows Users?

By default, the Recycle Bin folder ($Recycle.Bin) is enabled on the Windows host for deleted files. An individual Recycle Bin folder is created for each user in this directory on the RDS server (with the user’s SID as the name). Over time, you may find that the total size of the files in the Recycle Bin for all users will take up a significant amount of disk space on the RDS host.

$Recycle.Bin filters of other user profiles

The default size of the Recycle Bin in Windows is approximately 5% of the disk size. You can change the maximum size of the Recycle Bin on each drive in its properties. Here you can also disable recycle bin completely by using Do not move files to Recycle Bin Option. However, this will only change the Recycle Bin settings for the current user.

configure recycle bin options

You can set a maximum recycle bin size for users Maximum Allowed Recycle Bin Size GPO option under User Configuration -> Administrative Templates -> Windows Components -> File Explorer. The maximum Recycle Bin size is set as a percentage of your disk size. Setting this to 0 disables the Recycle Bin on all drives.

GPO: Maximum Recycle Bin Size Allowed

To clear the Recycle Bin in Windows, you can use clear-recycle bin cmdlet (available in PowerShell 5.1 and newer on Windows 10). To empty the Recycle Bin without prompting, run the following command:

Clear-RecycleBin -Force

If you run this command as a normal user on the RDS host, only the current user’s Recycle Bin will be cleared. You can add this command to your GPO log off script to clear the Recycle Bin when the user signs out:

%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command Clear-RecycleBin -Confirm:$false

For previous versions of Windows (including older versions of PowerShell), you can use the following code to clear the RecycleBin:

$Shell = New-Object -ComObject Shell.Application
$RecycleBin = $Shell.Namespace(0xA)
$RecycleBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}

Clear the Cache, Temp, and Downloads folders in User Profiles with PowerShell

Consider a PowerShell script to clean up Temp, Downloads and some other temporary folders in a user profile on a Windows Server RDS or desktop computer running Windows 10/11.

Script Comments:

  • In this example, we’ll delete files older than 14 Days in the Downloads folder (you can change this option). Other folders containing the cache and temporary files will be completely empty;
  • the script runs in the current user context (the script deletes old files when a user logs out of Windows and the GPO runs as a logoff script);
    If using in an RDS environment, make sure users click the Logout/Login button to end their sessions. We also recommend configuring the RDS session timeout to automatically expire sessions after a period of inactivity.
  • All information about deleted files will be saved in a text log file (you can disable it after debugging script on test users);
  • It will also clear the RDP connection history and cache;
  • The Windows Error Reporting (WER) folder in the user profile is cleared;
  • The lines that clear the Google Chrome cache are commented out in the script. Remove lines with paths if your users use it and the Chrome cache takes up a lot of space;
  • You can add an additional operation to check the current size of the User Profiles folder before and after the cleanup (this allows you to get more accurate information, but takes some time). Or you can check free disk space before and after (this is done quickly).
# You can use this script to clean folders in a user profile (cache, temp, downloads, google chrome cache) on RDS hosts, VDIs, or workstations
# Run the PowerShell script under a commaon user account (no administrator privileges are required). Only temporary files and the current user's cache are deleted.
# You can run this script via GPO (logoff script) or with the Task Scheduler
# Test the script in your environment and then remove the WhatIf option to permanently delete files
$Logfile = "$env:USERPROFILE\cleanup_profile_script.log"
$OldFilesData = (Get-Date).AddDays(-14)
# Complete cleanup of cache folders
[array] $clear_paths = (
    'AppData\Local\Temp',
    'AppData\Local\Microsoft\Terminal Server Client\Cache',
    'AppData\Local\Microsoft\Windows\WER',
    'AppData\Local\Microsoft\Windows\AppCache',
    'AppData\Local\CrashDumps'
    #'AppData\Local\Google\Chrome\User Data\Default\Cache',
    #'AppData\Local\Google\Chrome\User Data\Default\Cache2\entries',
    #'AppData\Local\Google\Chrome\User Data\Default\Cookies',
    #'AppData\Local\Google\Chrome\User Data\Default\Media Cache',
    #'AppData\Local\Google\Chrome\User Data\Default\Cookies-Journal'
)
# Folders where only old files should be removed
[array] $clear_old_paths = (
    'Downloads'
)
function WriteLog {
    Param ([string]$LogString)
    $Stamp = (Get-Date).ToString("yyyy/MM/dd HH:mm:ss")
    $LogMessage = "$Stamp $LogString"
    Add-content $LogFile -value $LogMessage
}
WriteLog "Starting profile cleanup script"
# If you want to clear the Google Chrome cache folder, stop the chrome.exe process
$currentuser = $env:UserDomain + "\"+ $env:UserName
WriteLog "Stopping Chrome.exe Process for $currentuser"
Get-Process -Name chrome -ErrorAction SilentlyContinue | Where-Object {$_.SI -eq (Get-Process -PID $PID).SessionId} | Stop-Process
Start-Sleep -Seconds 5
# Clean up cache folders
ForEach ($path In $clear_paths) {
    If ((Test-Path -Path "$env:USERPROFILE\$path") -eq $true) {
        WriteLog "Clearing $env:USERPROFILE\$path"
        Remove-Item -Path "$env:USERPROFILE\$path" -Recurse -Force -ErrorAction SilentlyContinue -WhatIf -Verbose 4>&1 | Add-Content $Logfile
    }
}
# Delete old files 
ForEach ($path_old In $clear_old_paths) {
    If ((Test-Path -Path "$env:USERPROFILE\$path_old") -eq $true) {
        WriteLog "Clearing $env:USERPROFILE\$path_old"
        Get-ChildItem -Path "$env:USERPROFILE\$path_old" -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {($_.LastWriteTime -lt $OldFilesData)} | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -WhatIf -Verbose 4>&1 | Add-Content $Logfile
    }
}
WriteLog "End profile cleanup script"

Similarly, you can add other folders that you want to clean up to the user profile. $clear_paths ,

This PowerShell script can run when the user’s RDP server session expires. The easiest way to assign a script is to use the Logoff GPO policy.

  1. Create a new GPO and assign it to the Organizational Unit (OU) in which your RDS hosts are located;
  2. Enable the Configure User Group Policy option loopback processing mode, This is necessary in order to apply the setting to the computer from the Users section; Enable GPO Loopback Processing
  3. Copy the PowerShell script file to the Net Logon folder on your domain controller (\\woshub.com\netlogon\CleanupUserProfile.ps1,
  4. Go to the GPO section User Configuration -> Policies -> Windows Settings -> Scripts -> Logoff. open powershell scripts Add UNC path to PS1 file in Tab and Netlogon;
  5. GPO: Run PowerShell script on logoffLog off the user from Windows for the new GPO setting to apply;
  6. When ending a user session on the RDS server, the specified folders will be automatically cleared. You can view the list of deleted files and folders in the text log file in the user profile.

Profile Cleanup Log

You can also use the following methods that allow managing user profile sizes on Windows Server RDS servers:

The user folder cleanup methods discussed here can be applied to both user profiles stored locally on Windows Server RDSH and to user profile disks or FSlogix profile containers.

Leave a Comment