Site icon WinCert

Completely Delete User Profiles with a Script

Here’s a useful script that will automatically delete ALL user profiles that are on a Windows Server 2008/R2 computer.

WARNING!
This is a dangerous operation, designed for use by an administrator who needs to do a complete purge; for instance at the end of a semester.

Note
For purposes of this example, we will use the following path for the script files:
D:\Scripts

cscript.exe “D:\Scripts\delete_profiles.vbs SRVNAME” > “D:\Scripts\profile_delete.txt”

Here is the code for the script file: delete_profiles.vbs

On Error Resume Next

args = WScript.Arguments.Count

If args <> 1 Then
  WScript.Echo "usage: delete_profiles SVRNAME"
  WScript.Echo "example (for remote profiles): cscript.exe delete_profiles SOMESERVER  "
  WScript.Echo "example (for local profiles): cscript.exe delete_profiles .  "
  WScript.Quit
End If

strComputer = WScript.Arguments.Item(0)
Set objWMIService = GetObject("winmgmts:\\" & strComputer &"\root\cimv2")
Set colProfiles = objWMIService.ExecQuery("Select * from Win32_UserProfile")
Wscript.Echo "==" & WScript.Arguments.Item(0) & "==" & vbNewLine

For Each objProfile in colProfiles
  Set objSID = objWMIService.Get("Win32_SID.SID='" & objProfile.SID &"'")
      If (objSID.ReferencedDomainName = "DOMAIN NAME") Then
      If Not ((objSID.AccountName = "USERNAME TO EXCLUDE") Or (Left (objSID.AccountName,2) = "USERNAME PREFIX TO EXCLUDE")) Then
          Set objUserProfile = GetObject("winmgmts:{impersonationlevel=impersonate}!\\" _
          & strComputer &"\root\cimv2:Win32_UserProfile." _
          &"SID='" & objProfile.Sid &"'")
          objUserProfile.Delete_
     Wscript.Echo objSID.AccountName & ";" & objSID.ReferencedDomainName & ";" & objProfile.LocalPath & " - " & "DELETED"
     End If
End If
Next

NOTES: In line 19 you have to specify the domain name to be used in the script and in line 20 you can specify user accounts that shouldn’t be deleted, like Administrator accounts.

Courtesy: KresimiK

Exit mobile version