Category filter
Script to delete inactive user profiles from Windows devices
Effective management of user profiles on Windows devices is essential for maintaining system performance, user privacy, and security. Unused user profiles can slow down devices and take up unnecessary storage. To address this issue, IT administrators can remove inactive user profiles after a set period using custom scripts.
This help document provides a PowerShell script that deletes inactive user profiles after a set number of days. IT administrators can deploy this script on Windows devices using Hexnode’s Execute Custom Script remote action.
Scripting language – PowerShell
File extension – .ps1
PowerShell script to delete inactive user profiles
1 2 3 4 5 6 7 8 9 10 11 12 |
$daysToKeep = Days $currentDate = Get-Date $profiles = Get-WmiObject Win32_UserProfile | Where-Object { $_.Special -eq $false } foreach ($profile in $profiles) { $lastUseDate = $profile.ConvertToDateTime($profile.LastUseTime) $daysSinceLastUse = ($currentDate - $lastUseDate).Days if ($daysSinceLastUse -ge $daysToKeep) { Remove-WmiObject -InputObject $profile Write-Host "Deleted profile $($profile.LocalPath)" } } Write-Host "Profile cleanup complete." |
The variable $daysToKeep sets the threshold day and is used in conjunction with the Get-WmiObject cmdlet to retrieve user profiles present on the device. Replace Days with the actual number of days you wish to retain the user profile after it was last used.
User profiles that have not been used in more than this specified number of days will be deleted. For example, if the number of days is set to 30, then user profiles that have not been used in the last 30 days will be deleted.
The PowerShell command $profiles = Get-WmiObject Win32_UserProfile | Where-Object { $_.Special -eq $false } retrieves the user profiles on the system. A loop is then initiated to iterate through each user profile present on the device. The script then calculates the number of days since the last use for each profile and checks whether it exceeds the number of days specified. If the condition is satisfied, then the script uses the Remove-WmiObject cmdlet to delete the user profile.
After the execution of the above script, user profiles that have remained inactive for more than the specified number of days will be deleted from the device.