If you wind up using this script, please leave a comment letting me know how it worked out for you!
Here is a batch file for cleaning user profiles in Windows 7. This was much easier in XP, but in Windows 7, you need to also clear out the registry values or you will get a Profile error on the next login by the cleared user. I couldn’t find any good ones online that met my needs perfectly, so I made my own.
One of the biggest criteria that I had was that I wanted to specify users for the script to leave alone. It seemed like anyone that made a script for profile deletion wiped the ground clean and I wanted to be able to retain users of my choosing. This is especially helpful in lab or library situations, to set this script as a logoff hook. There are two places that you would need to enter accounts to exclude from the wipe – one in the directory clean and one in the registry clean, just look for the commented areas below. Enjoy!
Change History:
Version 2.2 – Added server-reporting error verification
Version 3.0 – Nearly complete rewrite to account for appended (.001, .002, etc) profiles as well as providing cleaner code
Version 3.1 (Current) – Altered to work with user accounts that contain a space between two words.
@ECHO OFF :: -------------------------------------- :: :: Windows 7 User Profile Cleaning Script :: Version 3.1 :: :: Written by Mike Stone :: mikestone@gmail.com :: https://mstoneblog.wordpress.com :: :: -------------------------------------- :: :: Welcome! This script is designed to automate the process of flushing :: user profiles within Windows 7, while at the same time preserving :: profiles of your choosing, including domain users. :: :: This script is written as an example of wanting all domain users wiped :: except for the one called "pctest". :: :: Portions of the script that will require manual edits will be preceded :: by instructions with these "double colon" comment marks. :: :: Please let me know how well (or not well) this works for you or any :: features you can think of that could be added. :: :: -------------------------------------- title Windows 7 User Profile Cleaning :: ---------- :: Add any users you wish to exclude from the wipe to the "userpreserve" :: line below and separate them by commas. Be careful - these are :: case-sensitive. :: ---------- :USERPRESERVE set userpreserve="Administrator,All Users,UpdatusUser,Default,Default User,Public,pctest" 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 :REGCHECK set SPACECHECK= FOR /f "tokens=3,4" %%b in ('reg query %1 /v ProfileImagePath') DO SET USERREGPATH=%%b %%c FOR /f "tokens=2" %%d in ('echo %USERREGPATH%') DO SET SPACECHECK=%%d IF ["%SPACECHECK%"]==[""] GOTO REGCHECK2 GOTO USERCHECK :REGCHECK2 FOR /f "tokens=3" %%g in ('reg query %1 /v ProfileImagePath') DO SET USERREGPATH=%%g GOTO USERCHECK :USERCHECK FOR /f "tokens=3 delims=\" %%e in ('echo %USERREGPATH%') DO SET USERREG=%%e FOR /f "tokens=1 delims=." %%f IN ('echo %USERREG%') DO SET USERREGPARSE=%%f ECHO %USERPRESERVE%|find /I "%USERREGPARSE%" > NUL IF ERRORLEVEL=1 GOTO CLEAN IF ERRORLEVEL=0 GOTO SKIP :SKIP ECHO Skipping user clean for %USERREG% GOTO :EOF :CLEAN ECHO Cleaning user profile for %USERREG% rmdir "C:\Users\%USERREG%" /s /q > NUL ECHO Cleaning user registry for %USERREG% reg delete %1 /f IF EXIST "C:\Users\%USERREG%" GOTO RETRYCLEAN1 GOTO :EOF :RETRYCLEAN1 ECHO Retrying clean of user profile %USERREG% rmdir "C:\Users\%USERREG%" /s /q > NUL IF EXIST "C:\Users\%USERREG%" GOTO RETRYCLEAN2 GOTO :EOF :RETRYCLEAN2 ECHO Retrying clean of user profile %USERREG% rmdir "C:\Users\%USERREG%" /s /q > NUL GOTO :EOF :VERIFY FOR /f "tokens=*" %%g IN ('reg query "hklm\software\microsoft\windows nt\currentversion\profilelist"^|find /i "s-1-5-21"') DO CALL :REGCHECKV "%%g" GOTO REPORT :REGCHECKV set SPACECHECKV= FOR /f "tokens=3,4" %%h in ('reg query %1 /v ProfileImagePath') DO SET USERREGPATHV=%%h %%i FOR /f "tokens=2" %%j in ('echo %USERREGPATHV%') DO SET SPACECHECKV=%%j IF ["%SPACECHECKV%"]==[""] GOTO REGCHECKV2 GOTO USERCHECKV :REGCHECKV2 FOR /f "tokens=3" %%k in ('reg query %1 /v ProfileImagePath') DO SET USERREGPATHV=%%k GOTO USERCHECKV :USERCHECKV FOR /f "tokens=3 delims=\" %%l in ('echo %USERREGPATHV%') DO SET USERREGV=%%l FOR /f "tokens=1 delims=." %%m IN ('echo %USERREGV%') DO SET USERREGPARSEV=%%m ECHO %USERPRESERVE%|find /I "%USERREGPARSEV%" > NUL IF ERRORLEVEL=1 GOTO VERIFYERROR IF ERRORLEVEL=0 GOTO :EOF :VERIFYERROR SET USERERROR=YES GOTO :EOF :REPORT IF [%USERERROR%]==[YES] ( set RESULT=FAILURE ) ELSE ( set RESULT=SUCCESS ) :: ---------- :: This is fairly optional - it's just something I added so :: that I could keep an eye on the labs remotely to make :: sure there weren't masses of critical errors with the :: script failing. :: :: If you don't want it, just comment-out or remove the :: "net use" line. :: :: If you do want it, then make the necessary modifications :: to the net use to map an appropriate sharepoint. :: ---------- net use t: \\server\share IF EXIST "t:\labreport.txt" ( GOTO REPORTGEN ) ELSE ( GOTO EXIT ) :REPORTGEN FOR /F "tokens=*" %%n in ('echo %date:~10,4%-%date:~4,2%-%date:~7,2% %time:~0,2%-%time:~3,2%-%time:~6,2%') DO SET TDATETIME=%%n FOR /F "tokens=14" %%o in ('ipconfig^|find "IPv4 Address"') DO SET IPNUMBER=%%o ECHO. %RESULT% %COMPUTERNAME% %IPNUMBER% %TDATETIME%>>"t:\labreport.txt" net use t: /delete GOTO EXIT :EXIT exit :EOF
Mexico très équilibré a gagné leurs quatre derniers matches amicaux consécutifs contre la Bolivie, le Honduras, le Panama et l’équipe nationale du Bélarus Netherlands.
This works perfect thank you man. I needed something that would keep our administrator accounts in tact. (I work IT in a mid size company).
I believe that is one of the most important information for me. And i am happy reading your article. But wanna remark on few normal things, The website style is great, the articles is truly nice : D. Just right job, cheers|
Hi, Steve
Our roaming profiles start with numbers (ex: 47845) instead of an actual name (ex: tanderson). Looks like the script won’t delete those profiles that have number.
How do I modify the script so it can delete those profiles?
Thanks,
Thai Nguyen
Our roaming profiles are numbers (example: 478412) instead of the actual name. The script does not delete them at all.
How do I modify the script to make it work for roaming profiles start with the number?
the temp profiles are not deleted and the script that was posted :
Steve Crull
January 24, 2014 @ 9:07 am
I’ve modified the script to fix two things:
it is getting an error that 3 is unexpected
Hi
I am getting access denied on all profiles to be deleted on a windows 7 pc. ANy suggestions on why this is happening>?
Cheers
Hello Mike, I’d like to use this script. My technology level is strong intermediate.
My situation is very simple: Windows 7 Pro laptops NOT on a domain. Two local login accounts: one admin, one user. I thought I would just use the GUEST account for the user, but perhaps you’d advise differently.
The laptop(s) will be used by elementary school children in a computer lab.
My question is this: How do I actually employ the script to run at logoff for the limited user?
Hey Mike,
Great script by the way. I am wondering if there is an easy way run this script on a group of computers that are part of a text file. I don’t want to add it through a GPO or start up script. I would rather run this script every couple of months from our server that just targets a certain set of domain computers. Is there a way to do that?
Use PSExec. I have a modified version of this script that just deletes students, but leaves the admins profiles intact that I use to clean student computers. Works pretty good!
Using psexec you can just put the target comptuers in a text file, one per line and then run psexec against the text file and it will perform the command you want (whatever it is) on the computers in that list. You can make as many different lists as you need.
Doug
P.S. You can find PSEXEC online.
Works great, I used it on Windows 10 and Windows 7. Deleted all domain accounts from a student used computer. Nice work man!
Good Morning, I love your script but was wondering if it could be easily modified to delete one local profile (installer) rather than having to check thru the system?
Hi Steve. Thanks so much for your work on this script. Works perfectly!
I want to swap my users over to mandatory profiles and my test users work well. Before scaling to the whole school I’d like to enlarge the test group. Is there a way to specify an AD group to be deleted, or several AD groups to be excluded is the former isn’t possible?
Many thanks
The skript runs fine. BUT when you use “net user in cmd” , the user is still here !
And in the welcome screen also ! How can i fix this?
Awesome, copied into a bat file, made the change and it worked like a dream.
Thanks so much
Sorry to ask but when reading through your description all fields in “…” will require manual edits what is meant by “tokens=3,4”?
This worked like a charm with adding my needed exclusions! This was especially helpful after not being able to delete stale domain profiles via the GUI…even after a restart. Very well done and THANK YOU for sharing!
Thank you for script. It was of great help even.
Congratulations dedication and sharing.
God save the Brazil
The DeleteProfilesAfterXDays.bat works like a charm. I am testing it in a lab setting now and it works great! Thanks
I used this late-night when I was super-tired, without reading the instructions about “exclusions”, and wiped 15 days worth of my windows desktop files, the current Outlook 2010 PST, some images, and many Word documents!!
Thankfully, I did a Macrium Win.7 back-up on June 30th, and am currently using my re-furbed G5 to go online as I try to recover the deleted files in their least-corrupted state, but it’s NOT looking good, since the script effectively frags the clusters for the files it deletes- so PLEASE READ THE INSTRUCTIONS, FOLKS!
Nah it doesn’t touch the disk at all only the file system, so no ‘clusters’ are being fragged. Run TestDisk on the drive and see what you get.
I have used the this script but in a different fashion to it’s original design. I use it in part of a larger script to simply automate the removal of account directories on a non-AD connected system after I have deleted the accounts using ‘NET USER’.
Used the script with a couple modifications. We are using it in school labs and there is a user that never gets deleted that contains textharvester.dat. Following a technet article, I added lines to the script to start and stop the services that leave this user there.
At the top of the code:
net stop WSearch
net stop TabletInputService
At the end:
net start WSearch
net start TabletInputService
This works fine for that one user, but after restarting the machine, there are always 7 random users that remain in the C:/users folder, but not the registry, so if I run the script again, it doesn’t see them and doesn’t clean them out of the C:/users directory.
Any ideas on how I could resolve this? Currently just manually deleting out of C:/users but would love if we didn’t have to.
Thanks, this is still saving us loads of time!
This script does not work for me. Does anyone know what is wrong with it? I did notice that the If Exist line that looks for the existence of the report file is wrong. It had to be changed to IF NOT EXIST to get it to put the report file there.
On my systems, it just skips everybody and prints success to the report file and exits. Am I missing something?
Thanks. Please email me directly at doug.simpson@dierksschools.org and let me know if you had to do any other mods to get it to actually work.
Thanks!
Thanks Mike, the script runs great on Windows 7 machines. I haven’t tried it on a Windows XP Machine yet, do you know if this will work on a Windows XP machine?
Also, would it be easy to modify the script to make it delete accounts you want, instead of deleting all of the accounts not listed in UserPreserve parameter?
Thanks
Great script! Will this skip the currently logged in user as well?
I need to do the exact same thing but on Windows 8. Could someone provide me some advice ? Thanks a lot !
I cannot thank you enough. Works like a charm on my W2K8 TS. Stumbled onto your script after trying Delprof, Remprof among others.
Can anyone spot why it wouldnt remove a user that starts with a number?
Amazing Script! Thank you! As mentioned before by Michael, is there a version that targets specific user profiles to be deleted instead of all the user profiles?
That would rule beyond belief.
Thanks again!!
hello sir can u please tell me how to apply this script
I am only a simple end user but couldn’t you simply make the list of ones you do not want to delete in the do not delete section?
Thank You, thank you, this is JUST what I needed!
As a technician in the EDU environment, this is perfect for eliminating all those old student profiles, and freeing up HDD space!
Great script.. However, I have had to resort using this to using this script as a “Startup” script as sometimes the users NTUSER.DAT is in use and it will only wipe some of the profile. The Registry entries are removed successfully every time. However, with a half profile left behind it will not allow the user to login. After a successful reboot of a computer which would unlock the NTUSER.DAT the script does not look for orphan profiles under “C:\USERS”. Waiting a day or two before the user can login again wouldn’t be acceptable in our environment. Anyhow, great script.. Just wanted to share my thoughts.
See my modified script I’ve generated for other users on this page. It should do what you are looking for.
Its a permissions issue an you have to take full ownership to force delete the files.
Thank you Mike,
Work for me. Excellent for clean student profiles in my PC classroom.
thank you
Steve, The new script worked great. Is there a way you can modify the script to target specific profiles for cleaning. Say I have a PC running Win 7 that a user is having the temp profile issue with but others are working fine. Because it’s only one user I would like to remove that specific profile and registry entries without affecting all other profiles on the PC. Thanks for your help! :)
@ Steve Crull thanks for script as it works pretty well.
The only issue is that if the script doesn’t find the registry or the profile it shows Invalid Global Switch but it does the job very well
Thanks a lot and really sorry that i couldn’t reply at your post.
Sure thing. I have an idea of how that could done modifying this existing script. I’ll take a look at it in the morning
Awesome, saved us a lot of time. Thank you for the script
YOU COCKSUCKING MOTHERFUCKING!!! DELETE ALL FILES FROM DESKTOP FOLDER??? RLY??? DIE FOR CANCER YOU MOTHERFUCKER
This just made my day…lol…read through the script before you execute them next time…
y spam if you can execute the code in right manner
Wow……..dude. A good tech always tests before deploying across the enterprise. Live and learn I guess. Great script Steve!!!!!!!
I still can’t delete old profile that is more than XX numbers of days and please explain me how to add the date in the script and where as the script gets the job done but not in the right manner help will be appreciated as i have 2400 system of windows 7 that needs this script to be done
Sam,
Use this code in the for loops and change out the XX with the number of days old you want to check for:
forfiles /m NTUSER.dat /c “cmd /c Del testfile.txt ” /d -XX
The above code will check the NTUSER.dat last “written” date and will compare it to the days old variable you set. If there is a match you will get an exit code of 0. If there is not a match you will get an exit code of 1.
So, per account it would run this command and if a match was found you could have it then wipe the profile.
Correction:
forfiles /p C:\Users\%USERREG% /m NTUSER.dat /d -XX
Hi Steve,
Thanks for the prompt response for the code but it still seems to be functioning the same working as it deletes the user profile completely and i would be even grateful if you add and make the script of a new version with the below needs.
1.Delete the old profile with XX number of days and not delete the default profiles.
2.Delete the above old profile registry.
Again i would be grateful if you could make a script out of this and sorry for such trouble.
Sure thing. I’ll add it up here on Monday for you.
Hello Mike thanks for the script again.
But when a ran it on a system i get an error message like the below
Invalid Global Switch.
Skipping Deletion on Profile: rahulkanojia
ERROR: No files found with the specified search criteria.
Skipping Deletion on Profile: shankara
ERROR: No files found with the specified search criteria.
Skipping Deletion on Profile: nehas
ERROR: No files found with the specified search criteria.
Skipping Deletion on Profile: antonyb
ERROR: No files found with the specified search criteria.
note : this system is in domain and yes i executed this script directly on that machine and also sepecified the domain.
Apologies, I had a few revisions of the file floating around during testing. In the version I gave you it appears I forgot to change the ‘+’ to ‘-‘ next to the “days” variable. I’ve made the adjustment to the script which can be found here:
http://webpages.uncc.edu/~scrull/DeleteProfilesAfterXDays.bat
Sorry for the confusion. FYI – here is a link to the utility I’m basing the age variable off of if you need to tweak it further:
http://technet.microsoft.com/en-us/library/cc753551.aspx
Thanks a LOT Steve the script works perfectly will be testing for a week or so before deploying it on a larger network.
Again thanks a lot with out your help it would take a lot of pain to get this job done.
Hey Steve still waiting for that script that you were about to psot
Sorry for the delay Samuel, I got pulled away to other tasks this week. It’s a good thing I didn’t post it though as I found a bug in my code. I have since modified the code and worked out the bug. Currently, its set to delete any user account that isn’t marked as preserved or less than 3 days old. Anything 3 days or greater old would be deleted.
This number can then be modified to be any day amount you wish.
I’m running a couple final tests in the AM tomorrow and will let you know if everything worked as expected. Once I finish testing, where would you like me to send it for you?
Sam,
The script is ready and tested. Where would you like for me to post this for you?
Yes sure and thanks again for this script and your hard work
Actually, you can copy/paste it from here:
http://webpages.uncc.edu/~scrull/DeleteProfilesAfterXDays.bat
Hey Steve,
Did you find anything on that error which i posted above
Apologies, I had a few revisions of the file floating around during testing. In the version I gave you it appears I forgot to change the ‘+’ to ‘-‘ next to the “days” variable. I’ve made the adjustment to the script which can be found here:
http://webpages.uncc.edu/~scrull/DeleteProfilesAfterXDays.bat
Sorry for the confusion. FYI – here is a link to the utility I’m basing the age variable off of if you need to tweak it further:
http://technet.microsoft.com/en-us/library/cc753551.aspx
Sure thing! glad I could help out
Thank you a lot !
I would rather not post it up here on the blog. Can I message you on FB?
No problem. That works too.
https://www.facebook.com/steve.crull
Done. Thanks
Hmm, I’m not seeing anything come through on FB under my messages.
this is amazing
Thank you! Works beautifully and is going to save us a great deal of time!
Worked perfect! will save me a lot of time thanx a lot!
I would add disk clean up to tun at the end + restart
Your code is very usefull but how can we use it for remote PCs?
Is there anyone to change it for using Remote PCs.
Thank you in advance
Use PSexec to do that:
http://msdn.microsoft.com/en-us/library/bb897553.aspx
Without using PsExec please :)
I think this code can be used via adding SET /P
For Ex:
—————————–BAT CODE——————–
SET /P PC=Enter Host Name or IP For Ping Test:
ping %PC% -w 10 -t
pause
—————————————————————
How about Active Directory group policy? Just create a scheduled task to run the batch script as SYSTEM on a interval (every week, month, etc.). That’s how I do it.
If you want to do it on-demand for one-off machines, however, I’d use a remote execute tool such as Powershell or PSexec. If you use any endpoint management tools (BigFix, Altiris, SCCM, etc.) you could just have them execute the script locally with admin privileges.
Hi Mike,
The script works well :) is there any way or command that could be included to check number of days and based on our requirement the script deletes the profiles.
ex: Remprof has switch /D:( number of days) to check.
Worked like a charm!!! Thank you so much
Carl
Awesome, Thank you so much!
Thank you for the script, it appears to be working as intended. The only thing I have noticed are remnants of deleted domain profile folders. All the content within the profile folder was removed, however the actually folder itself still remained.
Do a scheduled reboot right before you run the script and it should dismount all ntuser data and allow for a smoother removal.
Hello Steve,
I am having the same issue as Hoon Choi. The script emptied out the contents of C:\Users\’AllUserNames’ and it correctly removes the registry entry. I am still left with the actual C:\Users\’AllUserNames’ folder though. The machines I have tested on have not had any users on them for several days as school is out for the summer. They had been rebooted several times prior to running the script.
Any suggestions?
Thank you,
Barry
What’s your email address? I’ll email you the script I’m using actively here in our labs. You can compare it to yours.
Hi Mike , i changed this line
:USERPRESERVE
set userpreserve=Administrator,All Users,UpdatusUser,Default,Default User,Public,
set userpreserve=%userpreserve%%username%,
this way the users on logon auto delete the others users.this way tehy do the job for you.
I’ve modified the script to fix two things:
1) If a user is still logged into the machine, it won’t touch their profile or files.
2) If the script deletes the user profile, but files still remain in C:\Users it will delete them.
@ECHO OFF
:: ======================================================================
:: SET LOGGED IN USER VARIABLE, IF AVAILABLE (MARK AS EXEMPT TEMPORARILY)
:: ======================================================================
for /f “tokens=3 delims=\” %%i in (“%USERPROFILE%”) do (set user=%%i) 2>&1
net stop WSearch
:: ======================================================================
:: EXEMPT ACCOUNTS
:: ======================================================================
:USERPRESERVE
set userpreserve=”Administrator,Default,Public,%user%”
:: ======================================================================
:: ENUMERATE NON-EXEMPT ACCOUNTS
:: ======================================================================
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
:: ======================================================================
:: DETERMINE IF SPACES ARE IN USERNAME
:: ======================================================================
:REGCHECK
set SPACECHECK=
FOR /f “tokens=3,4” %%b in (‘reg query %1 /v ProfileImagePath’) DO SET USERREGPATH=%%b %%c
FOR /f “tokens=2” %%d in (‘echo %USERREGPATH%’) DO SET SPACECHECK=%%d
IF [“%SPACECHECK%”]==[“”] GOTO REGCHECK2
GOTO USERCHECK
:REGCHECK2
FOR /f “tokens=3” %%g in (‘reg query %1 /v ProfileImagePath’) DO SET USERREGPATH=%%g
GOTO USERCHECK
:: ======================================================================
:: VERIFY USER ACCOUNTS ARE NOT EXEMPT FROM DELETION
:: ======================================================================
:USERCHECK
FOR /f “tokens=3 delims=\” %%e in (‘echo %USERREGPATH%’) DO SET USERREG=%%e
FOR /f “tokens=1 delims=.” %%f IN (‘echo %USERREG%’) DO SET USERREGPARSE=%%f
ECHO %USERPRESERVE%|find /I “%USERREGPARSE%” > NUL
IF ERRORLEVEL=1 GOTO CLEAN
IF ERRORLEVEL=0 GOTO SKIP
:: ======================================================================
:: EXEMPT USER – SKIP DELETION
:: ======================================================================
:SKIP
ECHO Skipping user clean for … %USERREG%
echo.
GOTO :EOF
:: ======================================================================
:: NON-EXEMPT USER – DELETE PROFILE
:: ======================================================================
:CLEAN
ECHO Cleaning user profile for … %USERREG%
echo.
RD /S /Q “C:\Users\%USERREG%” > NUL
ECHO Cleaning user registry for … %USERREG%
echo.
reg delete %1 /f
IF EXIST “C:\Users\%USERREG%” GOTO RETRYCLEAN1
GOTO :EOF
:RETRYCLEAN1
ECHO Retrying clean of user profile %USERREG%
echo.
TAKEOWN /F “C:\Users\%USERREG%” /r /d y
CACLS “C:\Users\%USERREG%” /T /E /G SYSTEM:F Administrator:F
RD /S /Q “C:\Users\%USERREG%” > NUL
GOTO :EOF
:: ======================================================================
:: VERIFY NON-EXEMPT ACCOUNTS DELETED PROPERLY
:: ======================================================================
:VERIFY
FOR /f “tokens=*” %%g IN (‘reg query “hklm\software\microsoft\windows nt\currentversion\profilelist”^|find /i “s-1-5-21″‘) DO CALL :REGCHECKV “%%g”
GOTO REPORT
:REGCHECKV
set SPACECHECKV=
FOR /f “tokens=3,4” %%h in (‘reg query %1 /v ProfileImagePath’) DO SET USERREGPATHV=%%h %%i
FOR /f “tokens=2” %%j in (‘echo %USERREGPATHV%’) DO SET SPACECHECKV=%%j
IF [“%SPACECHECKV%”]==[“”] GOTO REGCHECKV2
GOTO USERCHECKV
:REGCHECKV2
FOR /f “tokens=3” %%k in (‘reg query %1 /v ProfileImagePath’) DO SET USERREGPATHV=%%k
GOTO USERCHECKV
:USERCHECKV
FOR /f “tokens=3 delims=\” %%l in (‘echo %USERREGPATHV%’) DO SET USERREGV=%%l
FOR /f “tokens=1 delims=.” %%m IN (‘echo %USERREGV%’) DO SET USERREGPARSEV=%%m
ECHO %USERPRESERVE%|find /I “%USERREGPARSEV%” > NUL
IF ERRORLEVEL=1 GOTO VERIFYERROR
IF ERRORLEVEL=0 GOTO :EOF
:VERIFYERROR
SET USERERROR=YES
GOTO :EOF
:: =======================================================================================================
:: DETERMINE SCRIPT SUCCESS
:: =======================================================================================================
:REPORT
IF [%USERERROR%]==[YES] (
set RESULT=FAILURE
) ELSE (
set RESULT=SUCCESS
)
GOTO EXIT
:: =======================================================================================================
:: PERFORM FINAL CLEANUP EFFORTS – EXIT SCRIPT
:: =======================================================================================================
:EXIT
net start WSearch
IF [%RESULT%]==[SUCCESS] (
ATTRIB +H C:\Users\Administrator
ATTRIB +H C:\Users\Public
ATTRIB +H C:\Users\Default
FOR /D %%i IN (“C:\Users\*”) DO RD /S /Q “%%i” DEL /Q “C:\Users\*.*”
ATTRIB -H C:\Users\Administrator
ATTRIB -H C:\Users\Public
ATTRIB -H C:\Users\Default
)
pause
exit
:EOF
When i Try running this, now it wont delete any accounts.
Interesting. I run this regularly and haven’t run into that issue. try removing %user% from the exempt user accounts and re-run the script. Let me know if it runs properly. If that part is breaking ill develop an alternative.
tried to run this but getting 3 is not expected
Right now it looks like Drupal is the preferred blogging platform out there right now.
(from what I’ve read) Is that what you’re using on
your blog?
AWESOME JOB!! Any way of deleting the User Accounts from the computer too?
Under :CLEAN and :RETRYCLEAN1 and :RETRYCLEAN2 you could add this line:
net user %USERREG% /delete
That would wipe out the user account under computer management.
I need to delete unused profiles , but i need to deleted profile which is not used for more than 7 days and it should be working in non admin profile. need us assistance here..
Thanks in Advance.
Why don’t you just use this then? It has switches to check for idle accounts . This script is for on-demand blowing away of profiles. I’m sure you could script it, but no need to reinvent the wheel if someone already did it:
http://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/
Delprof2 /d:30
Deletes profiles older than 30 days on the local computer.
Hi Mike,
I need to delete unused profiles , but i need to deleted profile which is not used for more than 7 days. need you assistance
Hi Mike,
Adding another point it should be working in non admin profile
Hi Steve,
Thanks for sharing.
I have tried Delprof2, But it works only with Domain Admin’s account, it is not working in non admin users. Please let me know how can i run the script in Non admin users.
Under the :CLEAN and :RETRYCLEAN calls enter the following:
TAKEOWN /F “C:\Users\%USERREG%” /r /d /y
CACLS “C:\Users\%USERREG%” /T /E /G SYSTEM:F Administrators:F
RD /S /Q “C:\Users\%USERREG%” > NUL
That will resolve the profiles not fully deleting by taking ownership of them, then force deleting them.
Gali thank’s, tried this program http://ts-admin.com/vtra-tsprofcleaner-download and it works!
The easiest way clean profiles is to use this software . I tried it on my network and it works fine without any problam : http://ts-admin.com/vtra-tsprofcleaner-download
This is used for TS roaming profiles ONLY, this script works with the local profiles.
No , I cleaned local profiles from 120 computers on one of my sites with this software
Great software ! thak you Gali
How can we run this software without confirmation cause I going to use for school network. I can not go to each machine to run it. Thank you gali
Hi Mike,
Great script.
I do not have your knowledge. The profiles of all users are in the C:. Your script cleans properly.
For security, the folders and files stored by users files are located in D: / Library / Documents / Users Name /
I can not seem to adapt your code to clean up all the folders and files on all user profiles in the D:.
A little help please?
Thanks!
Thank you a bunch for sharing this with all of us you really
recognise what you are talking about! Bookmarked.
Please additionally consult with my site =).
We can have a hyperlink change contract between us
I am curious to find out what blog system you are using?
I’m having some small security issues with my latest site and I’d like to find something more safe.
Do you have any solutions?
Mike, Love the script. Work in a K-12 environment and this is great !!! Is there a way to force deletion of profiles even if there is files left in certain user profiles. Getting a lot of “the directory is not empty” errors while deleting. THANKS FOR ALL YOUR HELP :-) !!!!
I second this completely. While the script is still fantastic, I was forced to remove these folders manually after the script had run, which prevents me from setting this script to run automatically until I find a good a fix. Even so, thanks for this script; it’s a real time-saver.
Thank you very much!!!
Great script…adapted to meet our needs (large military campus with hundreds of profiles on thousands of computers). Ran on one computer,..exactly what I was looking for. I’m going to push to all computers and run monthly. Thank you!
Thank you so much. It is easy to read it and change it to match my needs.
Great job.
Thank you again.
Mike,
This looks like it’s exactly what I need, but I can’t seem to get it to do anything at a .bat file. I am new to .bat files, but I copied it exactly from your page and saved it on the desktop as a .bat file. Any suggestions?
Thank you for this script and your help!
Kevin
Is there a way to run this script from a local computer to clean up a remote computer on the network?
Do you have instructions how to use this.? thanks.
Very, very slick……
I like this…..a lot. I would like to see a little more error checking in the “net use” area (I know, it’s optional), but other than that, nice…..
Instead of removing every profile except for %userpreserve%, is it possible to remove *only* the specified profiles? I’m always scared to automate deletion of something that I didn’t directly specify.
I’ve read that the file left behind was due to the update service running which prevents the file from being deleted. I’ve tried putting in a net stop windows update services. I was still unable to delete several profiles.
I have the windows update service turned off via a GPO so i know that is not causing the issue.
Jermey,
I’m having the same issue for some reason the script does not delete all the user profiles.
The script seems to run pretty well except it doesn’t always remove the users folder fro C:\Users. If i show hidden files it looks like there is data i the appdata folder that is preventing it from deleting. Do you have any ideas how to correct this?
Is there a VB.Net way I can do this ? I need to run the app on a server to clean profiles from a set of shared machines. Any thoughts?
My partner and I absolutely love your blog and find a lot of your post’s to be just what I’m looking for.
Do you offer guest writers to write content in your case?
I wouldn’t mind composing a post or elaborating on a few of the subjects you write regarding here. Again, awesome web site!
Thank you so much for creating this excellent script! This is exactly what we were looking for to clean our labs and library computers. It cleans about 85% of the profiles. On question – How would I edit the script so it will clean off the remaining profiles with dual or triple initials? For example: ab.smith or a.b.smith
Mike, seems to be working well, school lab machines with hundreds of profiles – but watching the cmd screen I see a lof of “The directory is not empty” errors. Any idea what is causing this?
I have the same problem. Sometimes the Directory is not removed, even if it is empty. The script ends with SUCCESS.
I see in your script that you are trying to delete the folder 3 times (Retryclean1 and Retryclean2), but it still stays there. Any idea what is causing this?
It works pretty good, but one little thing. It didn’t delete all of the profiles, I had to do it manually. When I delete them manually I get the message ‘you’ll need to provide administrator permission to delete this folder’, when I click on continue it then deletes the folders. Is there a way to bypass this in the script. I am an admin on the PC and I have also tried running the script as an admin and it still does not delete all of the profiles.
I don’t want to delete the profile, only want to clean up things. Can the script be used just to clean-up the profile to get some much needed space back?
any update on if you could make this script only delete profiles that haven’t been modified in the last x number of days?
I second that. Been trying to find a way to make it work to delete profiles 14 days or older. I understand it’s free and am grateful, just wanted to make the suggestion.
Hi Mike. Nice script. Any easy way to add a group to the preserve list, like the Administrators group? that way I would not have to add every possible administrator account. Thanks, Sara
Also do you have a Powershell or VBS equivalent script?
:)
Hi mike I love the script works great for our workstation. just wondering do you have one for XP?
Mike,
I work in a K-12 environment where everyone from grade 3 up has there own account. This is GREAT! Thanks Mike!
All our student accounts are numerical, is there an easy way to tweak the file to delete only numerical accounts and leave the rest?
I think it may be – my initial off-the-cuff idea would require an answer to this question: do any of the “rest” of the accounts that you wish to save have any numbers in them or just letters?
The rest are just letters.
Do your accounts start with a number?
Thank you for the script Mike. It works for 80% of the profiles. The
remaining 20% are profiles with a space (i.e John Smith) and the batch tries to delete user John and tries for Smith and returns “The system cannot find the file specified”. Is there a workaround for this?
Just made the fix and released version 3.1. Please give it a try and let me know if it works any better – I was able to try it in small-scale ECHO debugs, but I don’t have an environment to TRULY duplicate the situation, so please provide a “yay” or “nay” as to the new functionality.
Genius!… I mean yay!
Works 100% for me now. Thank you very much Mike! ;o)
Just put out Version 3.0 to replace 2.4 put out over the weekend. Aside from some copy/pasting of select portions, this is a complete rewrite and has been very successful in my tests so far.
Version 2.4 is out which goes around the Windows 7 temp profile appending problem (Administrator.000, Administrator.001, etc)!
Finally a batch that works !!! Thanks Mike !!!
Michael,
Just wanted to tell you thank you for this script. I altered it to do the reverse, ONLY delete the profile mentioned in the PATHCHECK. This is extremely useful, as it allows me to deploy a GPO which runs this batch file and delete User Profiles for specific users across the enterprise. (e.g.: when an employee is terminated, I can add their username to this list and upon reboot, their profile will be deleted from all computers.)
Could you post the changes you made?
Heya, everyone. I have added to this script for remote reporting of success/fail so that I can monitor the progress of the client computers from my station and get solid data on how it is working in different labs.
I was thinking about the request to add date-based profile deletion, but I decided to not take up that mantle since there is a group policy object that allows for that. Maybe someday, but it’s not a high priority right now.
Nevermind. This script is perfect. Thanks!
Maybe I should read a bit more. I changed it to a batch file. I believe there are some permissions that I need to set. I am sure your script will work. Thanks!
I copied and pasted your script and saved it as a .vbs. I run this as a startup script, but it isn’t working for me. Am I missing something?
I am trying to get this to run through GPO.
Michael,
Thanks for the excellent script. Just what I was looking for to clean up a gazillion Vista/Windows 7 profiles.
Craig
I got it, Sorry i missed adding the accounts to the reg part.
I run this script on a 7 workstation and I excluded a few user accounts, what i’ve noticed is that the users that were excluded can no longer run app at a elevated privilege
i get an error from explorer.exe cant find .”///
yeah, we would like to limit the deletion to only profiles modified in the last 28 days as well as not deleting the administrator, public, default profiles. not sure how to go about that.
You know, that’s not a bad idea. I have some notions on how to make that happen and I’ve been meaning to do some core revisions anyway. I had some issues with some oft-frequently re-ghosted machines (lending laptops with hidden reghost partition) doing some funkiness with tacking a .000 to the end of some profiles which threw off this script a bit. Will work on this and post a new revision soon.
Any thought to adding a date check to your windows 7 profile deletion. Until we get our Domain controllers talking to each other – the Windows 7 autodelete “feature” does not seem to be working through group policy. I’m trying this script tonight but thought the date option might work better in our situation. Anyway – thanks for sharing the script.
brad
Maybe it would be possible for the script to look at the modify date of the profile folder and ignore the ones before a certain time? Not sure if that can even be done though.
What I do know is that the GP settings to delete a profile after so many days doesn’t work due to the file *.dat.LOG1 with in a profile. This file is used to determine that last logged time for any profile by the last modify date. However when Defender or in my case AV scans this file it is mark as modified on the time of being scanned. So… windows never see a profile older than 30 days.
Love the script, makes my life a lot easier!
Thanks Mike for sharing you work
Nathan,
It’s something I’ve looked into quite a bit. The big hitch with this is getting Windows to properly display the last date in which a user has logged in. Looking at the modified date of a user profile is disingenuous and problematic. If there were some way to run a command basically getting some form of output stating “user xxxxxx hasn’t logged in within xxxxx days”, then it would be an extremely simple process to implement.
I’ve thought of a few ways to make this happen, like another script to run at login that would make a hidden notation within a text file that could be referenced later, but I’m still not entirely sold on the idea. The thing I like about this is the simplicity of a single script.
Dunno – something for the future. Right now I’m pretty tied up at work developing a new Zero-Touch imaging system for WIM files and at home working on my Minecraft server. :)
Nathan,
I’ve implemented this feature in a revision of Mike’s code found here:
http://webpages.uncc.edu/~scrull/DeleteProfilesAfterXDays.bat