Scripting Question

Powershell to delete old local profiles..help!

10/14/2015 6780 views
As a requirement to clear disk space on some shared pcs where users are not meant to save data on , I need to delete local profiles older than 30 days.

I have put together the following script but keep getting  

" remove-item : Access to the path "C:\Users\user1\AppData\Local\Application Data is denied" 

this is strange because am running script with Admin priviledge and can manually delete files/folders in that directory. Can anyone shed some light on this? Any suggestion will be highly appreciated.

get-childitem "c:\users\" -exclude "Admin*", "All Users", "TEMP" ,"public", "Default" , "Default User" |? {$_.psiscontainer -and $_.lastwritetime -le (get-date).adddays(-30)} |% {remove-item $_ -Force}
1 Comment   [ + ] Show comment


  • The delprof tool does not work on newer versions of the Windows OS. There is another version delprof2 that does and you can set it up as a scheduled task with the t30 argument. It's free to educational groups. https://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/

All Answers

This tool works beautifully and can be deployed via a script.

Answered 10/14/2015 by: rockhead44
Red Belt

Try this.

You'll need a way to get the accounts on the machine, then pass them into a array so it can cycle through them. But the call below will use, you guess it, WMI to remove the profile. It works for local profile, not sure about Domain user accounts tho. Btw, careful when you delete profiles like the way your are doing it, there some other cleanup actions going on in the os background, sometimes you will end up with useracc.001 useracc.002 when they log back on (which turns into a profile nightmare)

$UserObj = Get-WmiObject Win32_UserProfile -filter "localpath='C:\\Users\\$LocalAccountName'"

Answered 10/15/2015 by: rileyz
Red Belt

Did you try -force switch?
Have a look at this article.
Answered 10/14/2015 by: dedenker
3rd Degree Black Belt

thanks for response dedenker I input the -force switch in the code ( see in the last pipe)

Answered 10/14/2015 by: TonyFishers
Yellow Belt

This website uses cookies. By continuing to use this site and/or clicking the "Accept" button you are providing consent Quest Software and its affiliates do NOT sell the Personal Data you provide to us either when you register on our websites or when you do business with us. For more information about our Privacy Policy and our data protection efforts, please visit GDPR-HQ