How can I delete all the “Account Unknown” profiles using a batch file?

Problem : How can I delete all the “Account Unknown” profiles using a batch file?

Is anyone aware of a way to delete all the “Account Unknown” user profiles listed on a workstation via a batch file?

Perhaps I’m drawing a blank but I can’t seem to think of a way to do it from the command line.  Please do not point out the “delprof.exe” utility from Microsoft as it is not designed to do this and won’t recognize anything listed as “Account Unknown”.

The domain is not using roaming profiles.  These “Account Unknown” profiles are remnants of some old local accounts that used to exist that were not deleted completely.  I basically want to delete anything that is an “Account Unknown” profile.

 

Solution : How can I delete all the “Account Unknown” profiles using a batch file?

Corrections to the corrections.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
@echo off
setlocal
 
REM Registry location of the profile list shown in System properties.
set reglist=HKLM\software\microsoft\windows nt\currentversion\profilelist
 
REM Queries the profile list for each profile's path
for /F "tokens=* usebackq" %%G in (`reg query "%reglist%"`) do (
 for /F "tokens=* usebackq skip=4" %%H in (`reg query "%%G" /v ProfileImagePath 2^>NUL`) do call :_process1 "%%G" "%%H"
)
goto :_end
 
:_process1
REM Subroutine to strip out the user name from the profile path.
for /F "tokens=1,2 delims=." %%J in ("%~n2") do call :_process2 "%~1" "%%J" "%%K"
goto :eof
 
:_process2
set active=
REM Corrects for user.domain profile paths
if "%~3"=="" (set prof=%~2) else (set prof=%~2.%~3)
REM Runs the net user command to determine if the username is valid locally
dir >NUL
net user %2 > NUL 2>&1
if "%errorlevel%"=="0" set active=true
REM Runs the net user command to determine if the username is valid on the domain
dir >NUL
net user %2 /domain > NUL 2>&1
if "%errorlevel%"=="0" set active=true
REM Checks for the built-in profiles
if /I "%~2"=="systemprofile" set active=true
if /I "%~2"=="LocalService" set active=true
if /I "%~2"=="NetworkService" set active=true
REM If none of the above conditions are met, deletes the profile's registry entry and folder.
if not defined active (
 echo reg delete %1 /f
 echo rd /q /s "%allusersprofile%\..\%prof%"
)
goto :eof
 
:_end
endlocal