Jump to content

Recommended Posts

Posted
Every half term I run a delprof script to delete profiles on xp and leave specified profiles, is there anything similar for windows 7?
Posted

We do it by policy just looked it up and it is something like this:

 

Policy: Delete user profiles older than a specified number of days on system restart

 

Category Path: Computer Configuration\Administrative Templates\System\User Profiles

 

This policy setting allows an administrator to automatically delete user profiles on system restart that have not been used within a specified number of days. Note: One day is interpreted as 24 hours after a specific user profile was accessed.

 

If you enable this policy setting, the User profile Service will automatically delete on the next system restart all user profiles on the computer that have not been used within the specified number of days.

TBH I am not sure this is exactly right but we definitely do it via GP

Posted
Yes I've seen that, but I like the script! Also I'd to be able to delete individual pofiles on an ad hoc basis much like using delprof in xp.
Posted (edited)

With Windows 7 you also need to remove something in the registery to manually delete profiles. Its pretty annouying to be honest.

 

You do this by doing the following:

 

 

To clear user local profile via registry :

 

1.Press on Start > Run >Regedit

 

2.Navigate to the following registry key :“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList”

 

3.Under ProfileList navigate to binary key’s like this :S-1-5-21-3656904587-1668747452-4095529-500

 

4.On the right side under ProfileImagePath you’’ll see the username and profile path.

 

5.Chose the one with the desired user and delete the long reg key like :“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList”

 

 

You can also look here on method one for a better idea

 

http://support.microsoft.com/kb/947215

 

 

 

Im not sure how to script it, im sure someone will though :)

Edited by FN-GM
  • Thanks 2
Posted

In Windows 7 if you don't want to go into the registry and delete the user profile keys a better way is to right click on Computer>properties>Advanced system settings>user profile settings>Highlight the required profile and then hit the delete button.

 

This deletes the user profile and also the registry keys with it.

 

If you just try to delete the user profile folder in C:\Users that user will not be able to log in to that workstation.

 

I am sure that some script guy could knock something up to run through GPO or even at the users log off. :D

Posted

Tried both the Computer>properties>Advanced system settings>user profile settings>Highlight the required profile and then hit the delete button and the regedit version.

Regedit was the winner!

A profile that previously showed the pupil background suddenly had the dreaded windows 7 black background, deleted the profile using the regedit way and background back with the new profile.

Posted
Tried both the Computer>properties>Advanced system settings>user profile settings>Highlight the required profile and then hit the delete button and the regedit version.

Regedit was the winner!

A profile that previously showed the pupil background suddenly had the dreaded windows 7 black background, deleted the profile using the regedit way and background back with the new profile.

 

Glad it work, its abit of a pain really. Im hoping someone will have a script one day :)

Posted
Glad it work, its abit of a pain really. Im hoping someone will have a script one day :)

 

You should have asked :-) I'm guessing you want something like the one below (and I'm sure I've already posted this but I can't find it now!)

 

The first chunk of this deletes the profiles that Windows knows about (ie the ones that show when you go to computer properties) - it does the registry clean up but sometimes fails to delete the folders on disc. The second part cleans up folders on disc which don't have a matching registry entry.

 

You need to run this at machine startup - that way there won't be any odd files held open (Windows 7 is much better at closing registry handles but just occasionally something gets left open)

 


const HKEY_LOCAL_MACHINE = &H80000002

set oDic=createobject("scripting.dictionary")
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Set oWMIService = GetObject("winmgmts:\\.\root\cimv2")
set oFSO=createobject("scripting.filesystemobject")
set oShell=createobject("wscript.shell")

on error resume next

'get a list of profiles; exclude "special" (stuff like localservice) profiles
Set colItems = oWMIService.ExecQuery("Select * from Win32_UserProfile where special=false and loaded=false",,48)
For Each oItem in colItems
 sSid=oItem.SID
 Set oUserProfile = GetObject("winmgmts:{impersonationlevel=impersonate}!\\.\root\cimv2:Win32_UserProfile.SID='" & sSID &"'")
 oUserProfile.Delete_
Next

'now clean up directories not attached to profiles
'and profiles not completely deleted by first step
'build a list of the directories used by profiles

sPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, arrSubKeys
For Each subkey In arrSubKeys
 lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath & "\" & subkey ,"ProfileImagePath",sDir)
 sDir=lcase(sDir)
 oDic.add sDir, subkey
Next

'now add the "fixed" profiles (public etc)

lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath ,"ProfilesDirectory",sRoot)
sRoot=lcase(oShell.expandenvironmentstrings(sRoot))
sRoot=sRoot & "\"

oDic.add sRoot & "public","public"
oDic.add sRoot & "all users", "all users"
oDic.add sRoot & "default","default"
oDic.add sRoot & "default user", "default user"

'look at each profile folder in turn
set oFolder=ofso.getfolder(sRoot)
for each oSubFolder in oFolder.subfolders
 sFolder=sRoot & lcase(oSubFolder.name)
 'check - is it in the list of "do not delete"
 if not(oDic.exists(sFolder)) then
   'orphaned folder so delete it
   ofso.deletefolder sFolder, true
 end if
next

  • Thanks 4
Posted
You should have asked :-) I'm guessing you want something like the one below (and I'm sure I've already posted this but I can't find it now!)

 

The first chunk of this deletes the profiles that Windows knows about (ie the ones that show when you go to computer properties) - it does the registry clean up but sometimes fails to delete the folders on disc. The second part cleans up folders on disc which don't have a matching registry entry.

 

You need to run this at machine startup - that way there won't be any odd files held open (Windows 7 is much better at closing registry handles but just occasionally something gets left open)

 


const HKEY_LOCAL_MACHINE = &H80000002

set oDic=createobject("scripting.dictionary")
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Set oWMIService = GetObject("winmgmts:\\.\root\cimv2")
set oFSO=createobject("scripting.filesystemobject")
set oShell=createobject("wscript.shell")

on error resume next

'get a list of profiles; exclude "special" (stuff like localservice) profiles
Set colItems = oWMIService.ExecQuery("Select * from Win32_UserProfile where special=false and loaded=false",,48)
For Each oItem in colItems
 sSid=oItem.SID
 Set oUserProfile = GetObject("winmgmts:{impersonationlevel=impersonate}!\\.\root\cimv2:Win32_UserProfile.SID='" & sSID &"'")
 oUserProfile.Delete_
Next

'now clean up directories not attached to profiles
'and profiles not completely deleted by first step
'build a list of the directories used by profiles

sPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, arrSubKeys
For Each subkey In arrSubKeys
 lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath & "\" & subkey ,"ProfileImagePath",sDir)
 sDir=lcase(sDir)
 oDic.add sDir, subkey
Next

'now add the "fixed" profiles (public etc)

lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath ,"ProfilesDirectory",sRoot)
sRoot=lcase(oShell.expandenvironmentstrings(sRoot))
sRoot=sRoot & "\"

oDic.add sRoot & "public","public"
oDic.add sRoot & "all users", "all users"
oDic.add sRoot & "default","default"
oDic.add sRoot & "default user", "default user"

'look at each profile folder in turn
set oFolder=ofso.getfolder(sRoot)
for each oSubFolder in oFolder.subfolders
 sFolder=sRoot & lcase(oSubFolder.name)
 'check - is it in the list of "do not delete"
 if not(oDic.exists(sFolder)) then
   'orphaned folder so delete it
   ofso.deletefolder sFolder, true
 end if
next

 

Just to double check that will work on Windows 7? Do you know if it works on Vista?

 

I know someone who has Server 2008 Terminal Servers so would be handy for getting rid of allot of profiles stored on there.

 

Thanks

Posted

Hi, I'm new to this site, but I thought I could contribute to this topic, since roaming profiles at my school have caused us quite a bit of agro.

 

I wrote this script to purge profiles from a windows 7 machine, but after reading your thread I quickly added the option to purge a single profile since you said you sometimes do that.

 

The script is vbs and takes 0, 1 or 2 arguments, the first argument is the name of the computer to purge profiles from, the second is a full or partial username string you can use to filter which profiles are deleted. If you dont specify a filter the script will delete all normal (ie not system, just normal user) profiles. If you dont specify a computer name it uses the local machine.

 

The script uses the Win32_UserProfile WMI class to delete user profiles and also removes the almost-empty folders that are sometimes left behind to prevent windows suffixing the domain name on a new folder and to keep things tidy. It's only been tested on windows 7 but will probably work on vista as well. Needless to say, it requires administrator privileges and does not interfere with profiles which are current in use.

 

I eventually replaced this script with a .net application that uses information from AD to wipe specific profiles from all our machines automatically. It uses a client service and a database to delete profiles we ask even if the machines are turned off and to make sure it doesn't remove profiles created after we triggered it. This would be difficult to post though. Nevertheless I don't use this script any more else I'd rewrite it in powershell, but it works and I hope it helps you.

 

Edit: Looks like someone beat me to it, but will leave it here anyway :)

 

On Error Resume Next

' ====================================
' Begin Force CSCRIPT Execution Engine
' ====================================
Dim objShell, strEngine, strArgs, strCmd, i
Set objShell = CreateObject("WScript.Shell")
strEngine = UCase(Right(WScript.FullName, 12))

If strEngine <> "\CSCRIPT.EXE" Then
   ' Recreate the list of command line arguments
   strArgs = ""
   If WScript.Arguments.Count > 0 Then
       For i = 0 To WScript.Arguments.Count
           strArgs = strArgs & " " & WScript.Arguments(i)
       Next
   End If

   ' Create the complete command line to rerun this script in CSCRIPT
   strCmd = "cscript.exe //nologo """ & WScript.ScriptFullName & """" & strArgs

   objShell.Run strCmd, 1

   WScript.Quit
End If
' ====================================
' End Force CSCRIPT Execution Engine
' ====================================

WScript.Stdout.WriteLine
WScript.Stdout.WriteLine "Avonbourne School Profile Deletion Script"
WScript.Stdout.WriteLine "========================================="
WScript.Stdout.WriteLine

Dim objFSO, objWMIService, strComputer, strFilter, colProfiles, objProfile

If WScript.Arguments.Count = 0 Then
strComputer = "."
ElseIf WScript.Arguments.Count = 1 Then
strComputer = WScript.Arguments(0)
strFilter = "SID Like ""S-1-5-21%"" And Not LocalPath Like ""%Administrator%"""
ElseIf WScript.Arguments.Count = 2 Then
strComputer = WScript.Arguments(0)
strFilter = "SID Like ""S-1-5-21%"" And LocalPath Like ""%" & WScript.Arguments(1) & "%"""
Else
WScript.Stdout.WriteLine "Invalid command line parameters."
WScript.Quit
End If

WScript.Stdout.WriteLine "Deleting profiles from '" & strComputer & "'..."
WScript.Stdout.WriteLine

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("Winmgmts:\\" & strComputer & "\root\cimv2") 
Set colProfiles = objWMIService.ExecQuery("Select * From Win32_UserProfile Where " & strFilter)

If Err.Number <> 0 Then
WScript.Stdout.WriteLine
WScript.Stdout.WriteLine "Error: " & Err.Number & ": " & Err.Description
WScript.Stdout.WriteLine
WScript.Exit
End If

If Not colProfiles Is Nothing Then
For Each objProfile in colProfiles
	WScript.Stdout.WriteLine "Processing profile: Path: " & objProfile.LocalPath
	WScript.Stdout.WriteLine "                    SID:  {" & objProfile.SID & "}"
	
	Err.Clear
	
	objProfile.Delete_
	
	If Err.Number = -2147024809 Then
		WScript.Stdout.WriteLine "                    Profile in use, skipping."
	ElseIf Err.Number = -2147024751 Then
		objFSO.DeleteFolder objProfile.LocalPath, True
		WScript.Stdout.WriteLine("                    Profile Deleted.")
	ElseIf Err.Number <> 0 Then
		WScript.Stdout.WriteLine " Failed!"
		WScript.Stdout.WriteLine
		WScript.Stdout.WriteLine "Error: " & Err.Number & ": " & Err.Description
		WScript.Stdout.WriteLine
	Else
		WScript.Stdout.WriteLine("                    Profile Deleted.")
	End If
Next
End If

  • Thanks 3
Posted
Just to double check that will work on Windows 7? Do you know if it works on Vista?

 

I know someone who has Server 2008 Terminal Servers so would be handy for getting rid of allot of profiles stored on there.

 

I'm using it on Windows 7 and it works fine. As far as I know, it works on Vista but I've not tried it (the WMI Win32_UserProfile stuff was introduced with Vista)

Posted
Hi, I'm new to this site, but I thought I could contribute to this topic, since roaming profiles at my school have caused us quite a bit of agro.

 

I wrote this script to purge profiles from a windows 7 machine, but after reading your thread I quickly added the option to purge a single profile since you said you sometimes do that.

 

The script is vbs and takes 0, 1 or 2 arguments, the first argument is the name of the computer to purge profiles from, the second is a full or partial username string you can use to filter which profiles are deleted. If you dont specify a filter the script will delete all normal (ie not system, just normal user) profiles. If you dont specify a computer name it uses the local machine.

 

The script uses the Win32_UserProfile WMI class to delete user profiles and also removes the almost-empty folders that are sometimes left behind to prevent windows suffixing the domain name on a new folder and to keep things tidy. It's only been tested on windows 7 but will probably work on vista as well. Needless to say, it requires administrator privileges and does not interfere with profiles which are current in use.

 

I eventually replaced this script with a .net application that uses information from AD to wipe specific profiles from all our machines automatically. It uses a client service and a database to delete profiles we ask even if the machines are turned off and to make sure it doesn't remove profiles created after we triggered it. This would be difficult to post though. Nevertheless I don't use this script any more else I'd rewrite it in powershell, but it works and I hope it helps you.

 

Edit: Looks like someone beat me to it, but will leave it here anyway :)

 

On Error Resume Next

' ====================================
' Begin Force CSCRIPT Execution Engine
' ====================================
Dim objShell, strEngine, strArgs, strCmd, i
Set objShell = CreateObject("WScript.Shell")
strEngine = UCase(Right(WScript.FullName, 12))

If strEngine <> "\CSCRIPT.EXE" Then
   ' Recreate the list of command line arguments
   strArgs = ""
   If WScript.Arguments.Count > 0 Then
       For i = 0 To WScript.Arguments.Count
           strArgs = strArgs & " " & WScript.Arguments(i)
       Next
   End If

   ' Create the complete command line to rerun this script in CSCRIPT
   strCmd = "cscript.exe //nologo """ & WScript.ScriptFullName & """" & strArgs

   objShell.Run strCmd, 1

   WScript.Quit
End If
' ====================================
' End Force CSCRIPT Execution Engine
' ====================================

WScript.Stdout.WriteLine
WScript.Stdout.WriteLine "Avonbourne School Profile Deletion Script"
WScript.Stdout.WriteLine "========================================="
WScript.Stdout.WriteLine

Dim objFSO, objWMIService, strComputer, strFilter, colProfiles, objProfile

If WScript.Arguments.Count = 0 Then
strComputer = "."
ElseIf WScript.Arguments.Count = 1 Then
strComputer = WScript.Arguments(0)
strFilter = "SID Like ""S-1-5-21%"" And Not LocalPath Like ""%Administrator%"""
ElseIf WScript.Arguments.Count = 2 Then
strComputer = WScript.Arguments(0)
strFilter = "SID Like ""S-1-5-21%"" And LocalPath Like ""%" & WScript.Arguments(1) & "%"""
Else
WScript.Stdout.WriteLine "Invalid command line parameters."
WScript.Quit
End If

WScript.Stdout.WriteLine "Deleting profiles from '" & strComputer & "'..."
WScript.Stdout.WriteLine

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("Winmgmts:\\" & strComputer & "\root\cimv2") 
Set colProfiles = objWMIService.ExecQuery("Select * From Win32_UserProfile Where " & strFilter)

If Err.Number <> 0 Then
WScript.Stdout.WriteLine
WScript.Stdout.WriteLine "Error: " & Err.Number & ": " & Err.Description
WScript.Stdout.WriteLine
WScript.Exit
End If

If Not colProfiles Is Nothing Then
For Each objProfile in colProfiles
	WScript.Stdout.WriteLine "Processing profile: Path: " & objProfile.LocalPath
	WScript.Stdout.WriteLine "                    SID:  {" & objProfile.SID & "}"
	
	Err.Clear
	
	objProfile.Delete_
	
	If Err.Number = -2147024809 Then
		WScript.Stdout.WriteLine "                    Profile in use, skipping."
	ElseIf Err.Number = -2147024751 Then
		objFSO.DeleteFolder objProfile.LocalPath, True
		WScript.Stdout.WriteLine("                    Profile Deleted.")
	ElseIf Err.Number <> 0 Then
		WScript.Stdout.WriteLine " Failed!"
		WScript.Stdout.WriteLine
		WScript.Stdout.WriteLine "Error: " & Err.Number & ": " & Err.Description
		WScript.Stdout.WriteLine
	Else
		WScript.Stdout.WriteLine("                    Profile Deleted.")
	End If
Next
End If

 

Thanks for posting. I will give it a shot.

 

Is this just ready to go as a startup script?

Posted

Its not really geared for a startup script, theres loads of output in there which can be stripped out. This would work better if all you want is to trash all user profiles in the machine logon script. Youll also need to ensure that this runs directly via cscript in the machine startup batch. If you let it run in wscript the computer wont wait for it to finish and users might be able to log in while its still running:

 

Dim objFSO, objWMIService, colProfiles, objProfile

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("Winmgmts:\\.\root\cimv2") 
Set colProfiles = objWMIService.ExecQuery("Select * From Win32_UserProfile Where SID Like ""S-1-5-21%"" And Not LocalPath Like ""%Administrator%""")

If Err.Number <> 0 Then
WScript.Exit
End If

If Not colProfiles Is Nothing Then
For Each objProfile in colProfiles
	Err.Clear
	
	objProfile.Delete_
	
	If Err.Number = -2147024751 Then
		objFSO.DeleteFolder objProfile.LocalPath, True
	End If
Next
End If

  • 2 weeks later...
Posted
You should have asked :-) I'm guessing you want something like the one below (and I'm sure I've already posted this but I can't find it now!)

 

The first chunk of this deletes the profiles that Windows knows about (ie the ones that show when you go to computer properties) - it does the registry clean up but sometimes fails to delete the folders on disc. The second part cleans up folders on disc which don't have a matching registry entry.

 

You need to run this at machine startup - that way there won't be any odd files held open (Windows 7 is much better at closing registry handles but just occasionally something gets left open)

 


const HKEY_LOCAL_MACHINE = &H80000002

set oDic=createobject("scripting.dictionary")
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Set oWMIService = GetObject("winmgmts:\\.\root\cimv2")
set oFSO=createobject("scripting.filesystemobject")
set oShell=createobject("wscript.shell")

on error resume next

'get a list of profiles; exclude "special" (stuff like localservice) profiles
Set colItems = oWMIService.ExecQuery("Select * from Win32_UserProfile where special=false and loaded=false",,48)
For Each oItem in colItems
 sSid=oItem.SID
 Set oUserProfile = GetObject("winmgmts:{impersonationlevel=impersonate}!\\.\root\cimv2:Win32_UserProfile.SID='" & sSID &"'")
 oUserProfile.Delete_
Next

'now clean up directories not attached to profiles
'and profiles not completely deleted by first step
'build a list of the directories used by profiles

sPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
oReg.EnumKey HKEY_LOCAL_MACHINE, sPath, arrSubKeys
For Each subkey In arrSubKeys
 lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath & "\" & subkey ,"ProfileImagePath",sDir)
 sDir=lcase(sDir)
 oDic.add sDir, subkey
Next

'now add the "fixed" profiles (public etc)

lRc=oReg.GetStringValue(HKEY_LOCAL_MACHINE, sPath ,"ProfilesDirectory",sRoot)
sRoot=lcase(oShell.expandenvironmentstrings(sRoot))
sRoot=sRoot & "\"

oDic.add sRoot & "public","public"
oDic.add sRoot & "all users", "all users"
oDic.add sRoot & "default","default"
oDic.add sRoot & "default user", "default user"

'look at each profile folder in turn
set oFolder=ofso.getfolder(sRoot)
for each oSubFolder in oFolder.subfolders
 sFolder=sRoot & lcase(oSubFolder.name)
 'check - is it in the list of "do not delete"
 if not(oDic.exists(sFolder)) then
   'orphaned folder so delete it
   ofso.deletefolder sFolder, true
 end if
next

 

 

Hi

 

I am getting the attached message. This is running it on a Server 2008 Terminal Server. Any ideas please?

Capture.PNG

Posted
Hi

 

I am getting the attached message. This is running it on a Server 2008 Terminal Server. Any ideas please?

 

Theres quite a lot of problems with that script, for example it re-queries wmi for a Win32_UserProfile object it already has before deleting it, also the code to iterate through registry entries looking for profile paths which shouldn't be deleted isn't needed because we already queried WMI for profile information. I've rewritten the script here which runs on my PC without error at least:

 

On Error Resume Next

Const HKEY_LOCAL_MACHINE = &H80000002

Dim objShell, objFSO, objProfilesFolder, objProfileFolder, objWMIService, objRegistry, colProfiles, objProfile, dicFoldersInUse, sProfilesFolderPath, sProfileFolderPath

Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("Winmgmts:\\.\root\cimv2") 
Set objRegistry = GetObject("Winmgmts:\\.\root\default:StdRegProv")
Set dicProfilePaths = CreateObject("Scripting.Dictionary")

Set colProfiles = objWMIService.ExecQuery("Select * From Win32_UserProfile")

If Err.Number <> 0 Then
WScript.Exit
End If

If Not colProfiles Is Nothing Then
For Each objProfile in colProfiles
	If objProfile.Special = False And objProfile.Loaded = False And Left(objProfile.SID, 8) = "S-1-5-21" And objProfile.LocalPath <> "" And InStr(1, objProfile.LocalPath, "administrator", 1) = 0 Then
		Err.Clear

		objProfile.Delete_
		
		If Err.Number = -2147024751 Then
			objFSO.DeleteFolder objProfile.LocalPath, True
		Else
			MsgBox "Error"
		End If
	Else
		dicProfilePaths.Add LCase(objProfile.LocalPath), objProfile.SID
	End If
Next
End If

objRegistry.GetStringValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList", "ProfilesDirectory", sProfilesFolderPath
sProfilesFolderPath = LCase(objShell.ExpandEnvironmentStrings(sProfilesFolderPath))

Set objProfilesFolder = objFSO.GetFolder(sProfilesFolderPath)

For Each objProfileFolder in objProfilesFolder.SubFolders
sProfileFolderPath = LCase(objProfileFolder.Name)

If (sProfileFolderPath <> "default" And sProfileFolderPath <> "default user" And sProfileFolderPath <> "public" And sProfileFolderPath <> "all users") Then
	sProfileFolderPath = sProfilesFolderPath & "\" & sProfileFolderPath
	If Not dicProfilePaths.Exists(sProfileFolderPath) Then
		objProfileFolder.Delete
	End If
End If
Next

Posted (edited)
Theres quite a lot of problems with that script, for example it re-queries wmi for a Win32_UserProfile object it already has before deleting it, also the code to iterate through registry entries looking for profile paths which shouldn't be deleted isn't needed because we already queried WMI for profile information. I've rewritten the script here which runs on my PC without error at least:

 

On Error Resume Next

Const HKEY_LOCAL_MACHINE = &H80000002

Dim objShell, objFSO, objProfilesFolder, objProfileFolder, objWMIService, objRegistry, colProfiles, objProfile, dicFoldersInUse, sProfilesFolderPath, sProfileFolderPath

Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("Winmgmts:\\.\root\cimv2") 
Set objRegistry = GetObject("Winmgmts:\\.\root\default:StdRegProv")
Set dicProfilePaths = CreateObject("Scripting.Dictionary")

Set colProfiles = objWMIService.ExecQuery("Select * From Win32_UserProfile")

If Err.Number <> 0 Then
WScript.Exit
End If

If Not colProfiles Is Nothing Then
For Each objProfile in colProfiles
	If objProfile.Special = False And objProfile.Loaded = False And Left(objProfile.SID, 8) = "S-1-5-21" And objProfile.LocalPath <> "" And InStr(1, objProfile.LocalPath, "administrator", 1) = 0 Then
		Err.Clear

		objProfile.Delete_
		
		If Err.Number = -2147024751 Then
			objFSO.DeleteFolder objProfile.LocalPath, True
		Else
			MsgBox "Error"
		End If
	Else
		dicProfilePaths.Add LCase(objProfile.LocalPath), objProfile.SID
	End If
Next
End If

objRegistry.GetStringValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList", "ProfilesDirectory", sProfilesFolderPath
sProfilesFolderPath = LCase(objShell.ExpandEnvironmentStrings(sProfilesFolderPath))

Set objProfilesFolder = objFSO.GetFolder(sProfilesFolderPath)

For Each objProfileFolder in objProfilesFolder.SubFolders
sProfileFolderPath = LCase(objProfileFolder.Name)

If (sProfileFolderPath <> "default" And sProfileFolderPath <> "default user" And sProfileFolderPath <> "public" And sProfileFolderPath <> "all users") Then
	sProfileFolderPath = sProfilesFolderPath & "\" & sProfileFolderPath
	If Not dicProfilePaths.Exists(sProfileFolderPath) Then
		objProfileFolder.Delete
	End If
End If
Next

 

Thanks, can you confirm that this works on Vista / 7 and cleans the registry etc?

 

Also can i add a few user profiles i want to keep eg administrator?

 

Just want to be 100% :)

Edited by FN-GM
Posted
We've not had any issues at all using delprof from the XP\Server 2003 toolkit on Windows 7 clients and Server 2008 R2 Terminal Servers. It runs every Friday at 4pm and seems to do the trick.
Posted
When i run the script its producing a message saying error. What casues this please?

 

Thanks

 

It means either you don't have permission or there are locked files in the profile folder which are preventing the folder from being deleted. This should not normally happen. There might be some issue here you need to investigate (ie why is there locked files in a profile which is not loaded).

 

To disable this message comment out the line:

 

MsgBox "Error"

Posted

I know what it is. Vmware tools is putting a file in there and locking it. Done a regedit to VMware and got rid of the profiles so it should be ok now.

 

Thanks

  • 2 months later...
Posted
Just to double check that will work on Windows 7? Do you know if it works on Vista?

 

I know someone who has Server 2008 Terminal Servers so would be handy for getting rid of allot of profiles stored on there.

 

Thanks

 

I wrote this batch script for AU - have it running as a scheduled task in all our lab and classroom machines. You can easily copy/paste profiles you need to preserve and it allows for remote logging of error reporting. This allows me to get nightly reports from our lab machines letting me know if any profiles are stuck.

 

@echo off

:START
FOR /f "tokens=*" %%a IN ('dir c:\USERS /b /ad') DO CALL :PATHCHECK "%%a"
GOTO REGISTRY

::The following is where you would put in the profile you wish to exclude from the wipe. Just copy/paste a line and make the appropriate revisions.

:PATHCHECK
IF /i [%1]==["Administrator"] GOTO :PATHSKIP
IF /i [%1]==["All Users"] GOTO :PATHSKIP
IF /i [%1]==["Default"] GOTO :PATHSKIP
IF /i [%1]==["Default user"] GOTO :PATHSKIP
IF /i [%1]==["public"] GOTO :PATHSKIP
GOTO PATHCLEAN

:PATHSKIP
ECHO. Skipping path clean for user %1
GOTO :EOF

:PATHCLEAN
ECHO. Cleaning profile for: %1
rmdir C:\USERS\%1 /s /q > NUL
IF EXIST "C:\USERS\%1" GOTO RETRYPATHFIRST
IF NOT EXIST "C:\USERS\%1" GOTO :EOF

:RETRYPATHFIRST
ECHO. Error cleaning profile for: %1 - Trying again.
rmdir C:\USERS\%1 /s /q > NUL
IF EXIST "C:\USERS\%1" GOTO RETRYPATHSECOND
IF NOT EXIST "C:\USERS\%1" GOTO :EOF

:RETRYPATHSECOND
ECHO. Error cleaning profile for: %1 - Trying again.
rmdir C:\USERS\%1 /s /q > NUL
GOTO :EOF

:REGISTRY
ECHO.------------
FOR /f "tokens=*" %%a IN ('reg query "hklm\software\microsoft\windows nt\currentversion\profilelist"^|find /i "s-1-5-21"') DO CALL :REGCHECK "%%a"
GOTO VERIFY

::The following is where it parses the registry data and checks it against the user path. Copy/paste the IF line and make the user modification needed.

:REGCHECK
FOR /f "tokens=3" %%b in ('reg query %1 /v ProfileImagePath') DO SET USERREG=%%b
IF /i [%USERREG%]==[c:\Users\Administrator] GOTO :REGSKIP
GOTO REGCLEAN

:REGSKIP
ECHO. Skipping registry clean for %USERREG%
GOTO :EOF

:REGCLEAN
ECHO. Cleaning registry for: %USERREG%
reg delete %1 /f
GOTO :EOF

::The cleaning portion of the script is now done. Now begins the verification and log reporting.

:VERIFY
FOR /f "tokens=*" %%c IN ('dir c:\USERS /b /ad') DO CALL :VERIFYPATH "%%c"

::Same thing as the clean - if you need to exclude an account, make your copy/paste below.

:VERIFYPATH
IF /i [%1]==["Administrator"] GOTO :EOF
IF /i [%1]==["All Users"] GOTO :EOF
IF /i [%1]==["Default"] GOTO :EOF
IF /i [%1]==["Default user"] GOTO :EOF
IF /i [%1]==["public"] GOTO :EOF
GOTO VERPATHREPORT

:VERPATHREPORT
ECHO. %1
IF /i [%1]==[] (
set PATHRESULT=PATH_SUCCESS
) ELSE (
set PATHRESULT=PATH_FAILURE
)
ECHO. %PATHRESULT%
GOTO REGVERIFY

:REGVERIFY
ECHO.------------
FOR /f "tokens=*" %%d IN ('reg query "hklm\software\microsoft\windows nt\currentversion\profilelist"^|find /i "s-1-5-21"') DO CALL :REGCHECKVERIFY "%%d"
GOTO REGVERIFYECHO

::Same thing as the registry clean - copy/paste excluded profiles below.

:REGCHECKVERIFY
FOR /f "tokens=3" %%e in ('reg query %1 /v ProfileImagePath') DO SET USERREGV=%%e
IF /i [%USERREGV%]==[c:\Users\Administrator] GOTO :EOF
GOTO REGVERIFYECHO

:REGVERIFYECHO
ECHO. %1
IF /i [%1]==[] (
set REGRESULT=REG_SUCCESS
) ELSE (
set REGRESULT=REG_FAILURE
)
ECHO. %REGRESULT%
GOTO REPORTCHECK

::The following is where you would enter the mapped drive path.
::You can use a straight UNC if you like, but I find this to be a bit
::more solid and it allows you to use different creds in case you
::automate it for a local scheduled task to run as local admin.

:REPORTCHECK
net use t: \\server\path

IF EXIST "t:\labreport.txt" (
GOTO REPORTGEN
) ELSE (
GOTO EXIT
)

::This is a time/date stamp creator that I actually pulled from a Minecraft
::to Dropbox backup script I made a long while back.

:REPORTGEN
FOR /F "tokens=1 delims=:" %%f in ('time /T') DO SET T=%%f
FOR /F "tokens=*" %%g in ('echo %date:~10,4%-%date:~4,2%-%date:~7,2% %T%-%time:~3,2%-%time:~6,2%') DO SET TDATETIME=%%g

ECHO. %PATHRESULT% %REGRESULT% %COMPUTERNAME% %TDATETIME% >> "t:\labreport.txt"
net use t: /delete
GOTO EXIT

:EXIT
exit

:EOF 

  • Thanks 1
Posted
I'm hoping someone will have a script one day

It can't get any simpler than this... :)

 

DelProf2.exe /u /i /r

 

http://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/

 

  • Delprof2 deletes inactive Windows user profiles (profiles that are not currently loaded).
  • Delprof2 is syntax compatible with the original Delprof by Microsoft. Unlike the original it works on Windows 7 (and XP/2003/Vista/2008/2008 R2).
  • If possible, Delprof2 uses the backup and restore privileges to bypass security and delete even profiles the executing user does not normally have access to.
  • Delprof2 has no problem whatsoever deleting files in very long paths (longer than MAX_PATH, 260 characters).
  • Delprof2 also cleans up stale ProfileList SID.bak registry entires, a common cause of temporary profiles.

  • Thanks 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...