Thanks to Microsoft breaking the "Delete user profiles older than a specified number of days on system restart" GPO and not fixing it after all of these years, I need a script that deletes old user profiles. The thing is that instead of it looking for the modification date of the user profile folder itself, I need it to delete the user profile based on the modification date of the Local folder in the Appdata folder of the user profiles. I noticed that the modification date of the user profile folder might not change for years even if you log in daily, but the local folder does seem to change depending on when you log in.
So, I have this that I grabbed from a spiceworks post made by user cxr-aus.
$useraccounts = Get-ChildItem -path C:\users\ | Where-Object lastwritetime -lt (Get-Date).AddDays(90) | Select-Object Name
$sort = $useraccounts | ForEach-Object {$_.Name}
$removeaccounts = $sort -join "|"
Get-WmiObject -Class Win32_userprofile | Where-Object {($_.LocalPath -match "$removeaccounts") -and (!$_.special)} | Remove-WmiObject -whatif
You would remove the -whatif at the end of the code to get it to remove a user profile. The first problem that I ran into is that I need this to remove multiple user profiles, so the Remove-WmiObject does not work because the Get-WmiObject returns multiple profiles for me, so to fix it to work, I use % { $_.Delete()} instead like the following.
WARNING:Be very careful with the following code as -whatif does not work with it and it might start deleting multiple profiles off of your machine.
$useraccounts = Get-ChildItem -path C:\users\ | Where-Object {$_.lastwritetime -lt (Get-Date).AddDays(90)} | Select-Object Name
Foreach ( $user in $useraccounts) {
$sort = $useraccounts | ForEach-Object {$_.Name}
$removeaccounts = $sort -join "|"
$Username = $removeaccounts.name
Get-WmiObject -Class Win32_userprofile | Where-Object {($_.LocalPath -match "$Username") -and (!$_.special)} | % { $_.Delete()}}
You can see that I did alter some other aspects of the code to try to break it up so that the code runs on one profile at a time. This kind of works as it will start deleting folders based on the Modification date of the user profile folder but the problem is it will delete user profiles that may have been used yesterday, but the modification date of the user profile folder did not change. So what I need the script to do is:
1.Get all of the user profiles folders in the C:\users directory
- Go into the user profile folder and get the modification date of the appdata\local folder.
3.Then return only user profile folders that the appdata\local folder has not been modified in this case for 90 days.
I have tried some things to alter this code that seem to be dead ends. Could Someone help me figure this out?