Script to Remove User Profiles Older than 30 Days

Welcome Forums General PowerShell Q&A Script to Remove User Profiles Older than 30 Days

Viewing 1 reply thread
  • Author
    Posts
    • #232525
      Inactive
      Topics: 1
      Replies: 0
      Points: 0
      Rank: Member

      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
    • #233359
      Participant
      Topics: 2
      Replies: 24
      Points: 87
      Helping Hand
      Rank: Member

      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.

      • This reply was modified 1 month, 1 week ago by Kris.
      • This reply was modified 1 month, 1 week ago by Kris.
Viewing 1 reply thread
  • You must be logged in to reply to this topic.