Forum Discussion

John Andrews's avatar
John Andrews
Copper Contributor
Nov 17, 2021

Windows 10 Delete User Profiles Older Than 60 Days

Hi. I am working on trying to automate cleaning up local user profiles on some machines that after awhile run into HDD space issues. I've been working on a script below for this, but I cannot get it to work quite right. I want to leave any profile that does not have a creation date older than 30 days. But it still deletes all profiles in the C:\Users folder. It doesn't seem to recognize the CreationTime on the profile, even though I can visually verify the date is within 30 days.

 

$Results = Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-30) -and $_.Name -ne "Public" -and $_.Name -ne "defaultuser0" -and $_.LocalPath -like "C:\Users\*"}
Foreach ($Temp in $Results)
{
$temp | Remove-CimInstance
Remove-Item -Path $temp.localpath -Recurse -force
}

4 Replies

  • IggyG10's avatar
    IggyG10
    Copper Contributor

    John Andrews 

    Very late response, but I am actually working on this same issue. This is what worked for me.

     

    I removed

    -and $_.Name -ne "Public" -and $_.Name -ne "defaultuser0" -and $_.LocalPath -like "C:\Users\*"}

    because

    | where {$_.Loaded -eq $false} |

    will replace this in my case.

     

    Finds and selects your users

    Get-CimInstance -ClassName Win32_UserProfile | Where {$_.CreationTime -lt (get-date).adddays(-60)} | where {$_.Loaded -eq $false} | select -Property LocalPath,Loaded,PSComputerName | ft -AutoSize

     

    Deletes your users

    Get-CimInstance -ClassName Win32_UserProfile | Where {$_.CreationTime -lt (get-date).adddays(-60)} | where {$_.Loaded -eq $false} | Remove-CimInstance -Verbose -Confirm:$false

     

    Not very pretty but it gets the job done.

    • peddy396's avatar
      peddy396
      Copper Contributor

       

      $currentDate = Get-Date

      $oneYearAgo = $currentDate.AddYears(-1)

       

      Get-WmiObject -Class Win32_UserProfile | ForEach-Object {

        if ($_.ConvertToDateTime($_.LastUseTime) -lt $oneYearAgo) {

          Remove-WmiObject -InputObject $_ -Confirm:$false

        }

      }

       

      Deploy as a startup script.  This works very well

       

       

  • SteveMacNZ's avatar
    SteveMacNZ
    Iron Contributor

    John Andrews 

     

    Hi John,

     

    This is what i use in my transcription log file clean up to clean up log files older than 15 days- may be of use...

    Get-ChildItem $PSScriptRoot -recurse "*$Script:ScriptName.log" -force | Where-Object {$_.lastwritetime -lt (get-date).adddays(-15)} | Remove-Item -force

     

Resources