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

Disclaimer:


The sample script provided below is adapted from a third-party open-source site.

PowerShell script to delete inactive user profiles

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.

Powershell script to delete inactive user profiles: action history tab showing the deleted user profile details as output

Notes:

  • Before executing the script, ensure that all data is securely saved. Deleting user profiles can potentially result in data loss, particularly if there is important data associated with the user profiles.
  • It is recommended to manually validate the script execution on a system before executing the action in bulk.
  • Hexnode will not be responsible for any damage/loss to the system on the behavior of the script.

  • Sample Script Repository