Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Last active October 5, 2024 10:05
Show Gist options
  • Save NiceRath/d4f826d9683e2156a35c71fcda41540c to your computer and use it in GitHub Desktop.
Save NiceRath/d4f826d9683e2156a35c71fcda41540c to your computer and use it in GitHub Desktop.
Windows RDS - Script to scheduled clean-up temporary user profiles
# Task Scheduler
# General
# Use local service-user of SYSTEM
# Enable 'Run whether user is logged in or not'
# Enable 'Do not store password'
# Enable 'Run with highest privileges'
#
# Action
# Program: C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe
# Arguments: -File C:\scripts\rds\RemoveTmpProfiles.ps1
# NOTE: task does not seem to delete folders if used with SYSTEM user (?)
$LOGFILE = 'C:\logs\tmpProfileCleanup.log'
$CHECK_DIR = "C:\Users"
$DAYS_LAST_USE = 7
echo ''
echo '### STARTING CLEANUP ###' | Tee-Object -Append -FilePath $LOGFILE
Get-Date | Tee-Object -Append -FilePath $LOGFILE
$TMP_PROFILE_DIRS = Get-ChildItem -Path "$CHECK_DIR" -Filter "TEMP.*" -Directory |? {($_.LastWriteTime -lt (Get-Date).AddDays(-$DAYS_LAST_USE))}
ForEach ($tmp_dir in $TMP_PROFILE_DIRS) {
$tmp_path = "$CHECK_DIR\$tmp_dir"
echo "Taking ownership of: '$tmp_path'" | Tee-Object -Append -FilePath $LOGFILE
$null = takeown /F "$tmp_path" /R /D y
echo "Removing: '$tmp_path'" | Tee-Object -Append -FilePath $LOGFILE
Remove-Item -Path "$tmp_path" -Recurse -Force -confirm:$false | Tee-Object -Append -FilePath $LOGFILE
echo ''
}
$BAK_PROFILE_DIRS = Get-ChildItem -Path "$CHECK_DIR" -Filter "*.BACKUP-*" -Directory |? {($_.LastWriteTime -lt (Get-Date).AddDays(-$DAYS_LAST_USE))}
ForEach ($bak_dir in $BAK_PROFILE_DIRS) {
$tmp_path = "$CHECK_DIR\$bak_dir"
echo "Taking ownership of: '$tmp_path'" | Tee-Object -Append -FilePath $LOGFILE
$null = takeown /F "$tmp_path" /R /D y
echo "Removing: '$tmp_path'" | Tee-Object -Append -FilePath $LOGFILE
Remove-Item -Path "$tmp_path" -Recurse -Force -confirm:$false | Tee-Object -Append -FilePath $LOGFILE
echo ''
}
Get-Date | Tee-Object -Append -FilePath $LOGFILE
echo '### FINISHED CLEANUP ###' | Tee-Object -Append -FilePath $LOGFILE
echo ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment