How to Delete Old User Profiles on Workstations Across a Network

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.

# 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:



Article ID: 797
Last updated: 27 May, 2020
Revision: 3
Third Party Products -> Windows Server -> Frequently Asked Questions (FAQ) -> How to Delete Old User Profiles on Workstations Across a Network
https://kb.stonegroup.co.uk/index.php?View=entry&EntryID=797