Skip to content

Instantly share code, notes, and snippets.

@jmconway
Created May 10, 2021 15:27
Show Gist options
  • Save jmconway/49705c59d5bf951e8885c06a93a0a691 to your computer and use it in GitHub Desktop.
Save jmconway/49705c59d5bf951e8885c06a93a0a691 to your computer and use it in GitHub Desktop.
Old PowerShell script used for removing cached local user profiles from a machine. Takes a parameter "Threshold" as integer such that profiles older than $Threshold days will be deleted. Uses WMI which has fallen out of fashion for CIM, but should still work. The delete method properly clears the registry and C:\Users as if done from the System …
# Clean User Profiles
# Makes WMI call to list profiles, excluding system accounts
# Deletes profiles whose LastUseTime is older than a set number of days
Param(
# Where-Object $Threshold is number of days as an integer; Profiles older than $Threshold days will be deleted
[Parameter(Position=0,Mandatory=$true)]
[int]$Threshold
)
# Convert $Threshold into a DateTime object for comparison
$cutoff = (Get-Date).AddDays(-$Threshold)
# Get list of all profiles; excludes system accounts, as well as the ulcshd, machineadmin, and profile accounts
$AllProfiles = Get-WmiObject Win32_UserProfile | Where-Object {$_.LocalPath -notlike '*\Windows*' | Select-Object LocalPath,@{Expression={$_.ConvertToDateTime($_.LastUseTime)};Label="LastUseTime"}
# Target profiles for removal
$TargetedProfiles = $AllProfiles | Where-Object {$_.LastUseTime -le $cutoff}
# If there are profiles that meet the criteria, delete them
if ($TargetedProfiles.count -ne 0) {
Foreach ($Profile in $TargetedProfiles) {
$OldProfile = Get-WmiObject Win32_UserProfile | Where-Object {$_.LocalPath -eq $Profile.LocalPath}
$OldProfile.Delete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment