Script to Remove User Profiles Older than 30 Days

Hi there,

I’ve been trying to work on a script that will remove any user profiles that are older than 30 days on some of the computers in my organization. I want the script to run the same as going to Control Panel > System > Advanced System Settings > User Profiles and deleting them from there. I’m pretty new to PowerShell, so don’t rip on me too hard lol. Here is what I have so far, but it’s not working. Any suggestions?

Get-CimInstance -Class Win32_UserProfile | Where-Object {($_.LastUseTime) -lt (Get-Date).AddDays(-30)} | Remove-CimInstance

Hi KSJohnson,

I clean up roaming profiles with this script (you can leave out the “roaming” part of course but if you do be careful not to delete the default or admin profiles):

$ThirtyDaysAgo = (Get-Date).AddDays(-30)
Function ConvertTo-DateTime {
Param(
  $DTGString
)
  $ConvertableDTGString= "{0} {1} {2}" -f $DTGString.Substring(0,4), $DTGString.Substring(4,2), $DTGString.Substring(6,2)
  [DateTime]$ConvertableDTGString
}

$Profiles = Get-WMIObject -Class Win32_UserProfile | Where-Object -Property RoamingConfigured -EQ $true
$Profiles | ForEach-Object {
  $User = $_.LocalPath.Replace("C:\Users\", "")
  $LastUsed = ConvertTo-DateTime -DTGString $_.LastUseTime
  If ($LastUsed -lt $ThirtyDaysAgo) {
    Remove-WmiObject -InputObject $_
  }
}

Every now and then the timing doesn’t work as supposed but in general it does the job.

Regards,

Kris.