Stone Computers Knowledgebase

How to Delete Old User Profiles on Workstations Across a Network

Article ID: 797
Last updated: 27 May, 2020
Article ID: 797
Last updated: 27 May, 2020
Revision: 3
Views: 65
Posted: 27 May, 2020
by Andrew Sharrad
Updated: 27 May, 2020
by Andrew Sharrad

How to Delete Old User Profiles on Workstations Across a Network

Old user profiles can consume large amount of space on shared network computers. This can be critical on some machines with relatively small Solid State hard drives.

Its a good idea to delete old user profiles from shared network Windows PCs to ensure that the drives do not run out of space. A number of methods have been around for some time, however recent changes to Windows 10 have broken a lot of these.

The attached Powershell script can be deployed via Group Policy as either a scheduled task, or a Computer Startup script.

  • The script can be configured with the maximum profile age. Profiles that have been modified after that date will be removed
  • You can specify that the script should not run on Windows Server operating systems
  • Lastly, you can specify a list of accounts for which the profile should never be deleted

# Delete old User Profiles
# Andrew Sharrad 14/5/2020

# Please test before widescale deployment

#The list of accounts, for which profiles must not be deleted
$ExcludedUsers ="Public","Default","itadmin"
$RunOnServers = $false
[int]$MaximumProfileAge = 120 # Profiles older than this will be deleted

$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem

if ($RunOnServers -eq $true -or $osInfo.ProductType -eq 1) {

    $obj = Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special -and $_.Loaded -eq $false )}
    #$output = @()

    foreach ($littleobj in $obj) {
        if (!($ExcludedUsers -like $littleobj.LocalPath.Replace("C:\Users\",""))) {
            $lastwritetime = (Get-ChildItem -Path "$($littleobj.localpath)\AppData\Local\Microsoft\Windows\UsrClass.dat" -Force ).LastWriteTime
            if ($lastwritetime -lt (Get-Date).AddDays(-$MaximumProfileAge)) {
                $littleobj | Remove-WmiObject
              #  $output += [PSCustomObject]@{
              #      RemovedSID = $littleobj.SID
              #      LastUseTime = $litteobj.LastUseTime
              #      LastWriteTime = $lastwritetime
              #      LocalPath = $littleobj.LocalPath
              #  }
            }
        }
    }

#$output | Sort LocalPath | ft
}

Note: Always test this script before wide-scale deployment.

Applies to:

  • Windows computers running on a network

This article was:  
Article ID: 797
Last updated: 27 May, 2020
Revision: 3
Views: 65
Posted: 27 May, 2020 by Andrew Sharrad
Updated: 27 May, 2020 by Andrew Sharrad