How to delete user profile remotely using PowerShell script

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

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

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 as 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, special System and Network Service accounts, a local administrator account, users with active sessions, 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 the launch of this script through the shutdown script of the Group Policy or on a schedule by the scheduler task. (Before setting up automatic deletion of profiles, test the script carefully in your environment!).

Now furthermore you can also modify this script to automatically delete users of all users who are added to a specific AD group. For example, if the user leaves from the company you can maintain the profile for a number of 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()}
%d bloggers like this: