How to delete user profile remotely using PowerShell script

When you log in to Windows for the first time, windows creates a user profile and interactively logs on to the computer. It contains a user registry (ntuser.dat), user-specific folders (My Documents, Desktop, etc.), and an Application Data folder that stores software-specific data about the user.

Deleting the user profile from the physical PC is easy, but now we will be looking at how to remotely delete a user profile from the command line tool.

Using the below command, we are trying to display a list of users whose profile has not been used for more than 60 days. You can change the value of the LastUseTime profile field for searching for any number of days per your needs.

Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-60))}| Measure-Object

To remove all these profiles, it is enough to add a redirect list to the Remove-WmiObject command (before using the removal script, it is advisable to double-check its output using the -WhatIf parameter):

Get-WMIObject -class Win32_UserProfile | Where {(! $ _. Special) -and (! $ _. Loaded) -and ($ _. ConvertToDateTime ($ _. LastUseTime) -lt (Get-Date) .AddDays (-30))} | Remove-WmiObject –WhatIf

In order not to delete the profiles of some users, for example, particular System and Network Service accounts, a local administrator account, users with active sessions, and a list of excluded accounts), you need to modify the script as follows:

# List of accounts whose profiles cannot be deleted $ExcludedUsers ="Public","zenoss","svc",”user_1”,”user_2” $LocalProfiles=Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and (!$_.Loaded) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-60))} foreach ($LocalProfile in $LocalProfiles) { if (!($ExcludedUsers -like $LocalProfile.LocalPath.Replace("C:\Users\",""))) { $LocalProfile | Remove-WmiObject Write-host $LocalProfile.LocalPath, "профиль удален” -ForegroundColor Magenta } }

You can configure this script’s launch through the Group Policy’s shutdown script or on a schedule by the scheduler task. (Before setting up the automatic deletion of profiles, test the script carefully in your environment!).

Furthermore, you can modify this script to automatically delete users of all users who are added to a specific AD group. For example, if the user leaves the company, you can maintain the profile for several days and later, you can delete it automatically without remembering.

$users = Get-ADGroupMember -Identity ResignedUsers | Foreach {$_.Sid.Value} $profiles = Get-WmiObject Win32_UserProfile $profiles | Where {$users -eq $_.Sid} | Foreach {$_.Delete()}

Was this Article Helpful?

Did I just helped you solve one of your problem? Support me by buying me a coffee. Thanks for your support