Thursday, April 28, 2011

Windows 7 temporary profile after profile cleanup

After cleaning up a userprofile on a Windows 7 station (Deleting folders “c:\users\MyUserAccount” and the roaming profile on “\\fs01\profiles\MyUserAccount”) i thought i would start with a clean profile.
But Windows kept logging user “MyUserAccount” in with a temporary profile.

It seems that Windows keeps a list of profile locations in the registry. If that location for a certain user can’t be found, the user is logged on with a temporary profile.
This is the key:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

What you see there is a lists of profile SID’s, so you have to check them all out to find your user and delete the whole key accordingly.

I thought it would be handy to write a script that automates this.
It checks for a key called “ProfileImagePath” and if the value in that key (e.g. c:\users\JohnDoe) doesn’t exist on the local system, it wipes the whole registry key from the ProfileList.

Save as W7ProfileListCleanup.vbs:

ON ERROR RESUME NEXT

'### GLOBAL VARIABLES
Dim WSHShell, oFSO, strComputer, ProfileListRegistryLocation, ArrayWithProfileSIDS, Subkeys, HKEY_LOCAL_MACHINE

'### CREATE OBJECTS
Set WSHShell = CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
strComputer = "."
Set objRegistry = GetObject("winmgmts:\" & strComputer & "\root\default:StdRegProv")

'### CONSTANTS
HKEY_LOCAL_MACHINE = &H80000002
ProfileListRegistryLocation = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
RegistryKeyContainingPath = "ProfileImagePath"

'### FUNCTIONS NEEDED
Function CheckAndDelete(LocalProfileDir, ProfileSID, FullPath)
  If not oFSO.FolderExists(LocalProfileDir) then
    WScript.Echo "NOT FOUND: " + LocalProfileDir
    DeleteProfileListKeyRecursive FullPath
  else
    WScript.Echo "OK:        " + LocalProfileDir
  end if
End Function

Function DeleteProfileListKeyRecursive(FullPath)
  WSHShell.Run "reg delete ""HKLM" + FullPath + """ /f", 0, True
  WScript.Echo "- Deleted: " + FullPath
End Function
'### END OF FUNCTIONS NEEDED

'### START THE ACTION

'### ENUMERATE THE LIST WITH PROFILES
objRegistry.EnumKey HKEY_LOCAL_MACHINE, ProfileListRegistryLocation, ArrayWithProfileSIDS

For Each ProfileSID In ArrayWithProfileSIDS
  FullPath = ProfileListRegistryLocation & "" & ProfileSID
  objRegistry.GetExpandedStringValue HKEY_LOCAL_MACHINE, FullPath, RegistryKeyContainingPath, LocalProfileDir
  '### CHECK FOR DIRS AND DELETE IF NOT FOUND
  CheckAndDelete LocalProfileDir, ProfileSID, FullPath
Next