In this post, I’ll discuss how I created a PowerShell script that runs when a user logs out of a terminal server and cleans up a directory in their home folder that was filling up with space due to application crashes.
This is the script I created:
$username = $ENV:USERPROFILENAME $testpath = Test-Path -Path "$username\AppData\Local\Microsoft\Windows\ApplicationFolder" if ($testpath -eq $true){ $items = Get-ChildItem - Path "$username\AppData\Local\Microsoft\Windows\ApplicationFolder" foreach($i in $items){ Remove-Item -Path "$username\AppData\Local\Microsoft\Windows\ApplicationFolder\$i" -Recurse -Confirm:$FALSE } }else{}
This code will get the users profile root path and then check if the application folder exists, if it doesn’t then the script ends. If it does exist, the script will cycle through each entry and remove it.
The -Confirm:$FALSE parameter was added because the script kept asking for confirmation when deleting each item. This stops this behaviors and deletes each item without a confirmation prompt.
Now that I have the script and it is working as expected, I create a local group policy that will use:
Name – “powershell.exe”
Parameters – “-F “C:\path\to\file.ps1”
You can see this in the screenshot below:
This group policy was added under:
User Configuration – Windows Settings – Scripts (Logon/Logoff) – Logoff
Hopefully you can replicate what I have done and don’t experience any issue. Note that you might need to change the script execution policy on the machine before this works properly. Just something to keep in mind if the group policy isn’t working. Enjoy!