Quick Tips: Programmatically emptying the Temp folder for all user profiles in a terminal server.

     

I ended up needing to do this last week, we have a LOB application that people access via Terminal Services, and it doesn’t clean up after itself in the Temp folder, which causes the application to act up. Can’t get the developers to fix the problem so it’s on us. The existing fix was one batch file, tied to one scheduled task, for every user (50+) of the terminal server. Nightmare to keep maintained.

So I built a simple powershell script, one script for all user profiles.

for(;;) {
     try {
         Set-Location "C:\Users"
         Remove-Item ".\\\*\AppData\Local\Temp\\\*" -recurse -force
     }
 catch {
     # EventSentry will watch for Powershell dying.
     Break
 }

 # wait for a minute
 Start-Sleep 60
}

Then I created a scheduled task to have Powershell run on startup with the argument -file Path:\to\script.ps1 and had it run as SYSTEM with highest privileges. Since this was the first time using ps1 files on this server I also needed to Set-ExecutionPolicy RemoteSigned.

comments powered by Disqus