Question

Temp files deletetion script does not clear all profiles and all temp folders.

Asked by: bsharath

Hi,
Temp files deletetion script does not clear all profiles and all temp folders.
sedgwick has given me this code.

it does not clear all and every temp folder and from the profiles. If Vista it needs to remove accordingly.

Regards
Sharath

@echo off
cls
if not exist %systemroot%\DelTempSched.bat (
copy %0 %systemroot%\DelTempSched.bat > nul  
reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v TempDelScheduler /t REG_SZ /d %systemroot%\DelTempSched.bat /f > nul
)
 
schtasks /query > doh.txt
findstr /B /I "Temp-deletetion" doh.txt >nul
if not %errorlevel%==0  (
SCHTASKS /CREATE /sc DAILY /ST 11:45 /TN "Temp-deletetion" /TR %systemroot%\DelTempSched.bat /RU "NT AUTHORITY\SYSTEM" >nul
 
echo %DATE% %TIME% User: %USERNAME% - Task schduler 'Temp-deletetion' was creared. > \\inm\Logs\TempDelTask.log
)
 
rd /s /q "%temp%\..\"
md "%temp%\..\"
 
rd /s /q "c:\windows\temp"
md "c:\windows\temp"
 
rd /s /q "%Userprofile%\AppData\Local\temp"
md "%Userprofile%\AppData\Local\temp"
 
rd /s /q "%Userprofile%\Local Settings\Temporary Internet Files"
md "%Userprofile%\Local Settings\Temporary Internet Files"
 
rd /s /q "%Userprofile%\Local Settings\temp"
md "%Userprofile%\Local Settings\temp"
 
@echo off
FOR /F "tokens=*" %%G IN ('DIR /B /AD C:\Documents and Settings') DO (
echo %%G
IF EXIST "C:\Documents and Settings\%%G\Local Settings\Temp" ( 
    RMDIR /S /Q "C:\Documents and Settings\%%G\Local Settings\Temp" 
    MKDIR "C:\Documents and Settings\%%G\Local Settings\Temp" 
    Echo Cleared C:\Documents and Settings\%%G\Local Settings\Temp 
    Echo Cleared C:\Documents and Settings\%%G\Local Settings\Temp	>> \\inm\Logs\TempDelTask.log
) 
)
 
FOR /F "tokens=*" %%G IN ('DIR /B /AD C:\Documents and Settings') DO (
echo %%G
IF EXIST "C:\Documents and Settings\%%G\Local Settings\Temporary Internet Files" ( 
    RMDIR /S /Q "C:\Documents and Settings\%%G\Local Settings\Temporary Internet Files" 
    MKDIR "C:\Documents and Settings\%%G\Local Settings\Temporary Internet Files" 
    Echo Cleared C:\Documents and Settings\%%G\Local Settings\Temporary Internet Files 
    Echo Cleared C:\Documents and Settings\%%G\Local Settings\Temporary Internet Files	>> \\inm\Logs\TempDelTask.log
) 
)
 
FOR /F "tokens=*" %%G IN ('DIR /B /AD C:\users') DO (
echo %%G
IF EXIST "C:\users\%%G\AppData\Local\temp" ( 
    RMDIR /S /Q "C:\users\%%G\AppData\Local\temp" 
    MKDIR "C:\users\%%G\AppData\Local\temp" 
    Echo Cleared C:\users\%%G\AppData\Local\temp 
    Echo Cleared C:\users\%%G\AppData\Local\temp	>> \\inm\Logs\TempDelTask.log
) 
)
 
del doh.txt >nul
                                  
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:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-04 at 02:39:17ID24870395
Tags

Script

,

Bat

,

vbs

Topics

Programming Languages

,

Scripting Languages

,

Windows Batch Scripting

Participating Experts
2
Points
500
Comments
47

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Domain User Always Uses The TEMP profile when logging i…
    I have a VISTA Universal PC that I joined to a domain. Unfortunatly, I tried the old XP trick of adding the domain user to the PC administrators group, logging in as the user to create a new profile, then logging in as admin and copying the directories under \Users\%olduserna...
  2. TEMP Profile question
    I have a user that is trying to access his locally stored profile on his machine. When he logs into the network, he's not given any of his settings. It's like he's logging on for the first time. I can see another profile on the machine (which has the settings he needs) but...
  3. Vista, domain user profile status is temp
    I am having a problem with domain user profiles on a vista machine. My objective is to copy a local user profile to the users new domain profile. I am unable to do this because the domain user profile status is temp, so I cannot perform the copy to function. Does anyone know...
  4. Roaming profiles creating temp folder ? On Vista/SBS2008
    I having problems with only one machine in a network we created, the other 4 machines are working fine. Whenever you log on with a roaming profile it creates a temp profile and therefore doesn't save settings locally when you log on next time. This is the same for all user a...
  5. Create a scheduled task on every machine on startup to del…
    Hi, Create a scheduled task on every machine on startup to delete the temp files. Schedule task name : Temp-deletetion Description: Created by ICT Time: 11.45 AM Each restart check if schedule task there if no then create one. If exists then do nothing. record the success ...
  6. What are all the temp files locations in a Windows XP and vi…
    Hi, What are all the temp files locations in a Windows XP and vista machine. I need help listing all the locations that we can clear to get space on a machine periodically C:\Windows\temp all locations Temp internet/Cookies/Temp files and any for both the operating systems...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sedgwickPosted on 2009-11-04 at 05:03:41ID: 25738835

bsharath: why did u close the thread if it wasn't working for you?
anyway, when u run the script from the console, u should see the output for almost every line.
when u say it doesn't clear all temp folders, try to delete them yourself and see if u get popup saying Destination Folder Access Denied - You need permission bla bla, like the attached image.
if u manage to delete them manually something is wrong with the script.

 

by: bsharathPosted on 2009-11-04 at 06:29:54ID: 25739577

Your scriupt does work but not on all profiles. I created few folders and files those also did not delete. Any ways...Can you see the attached script which i use to remotely delete. if some thing like this can be added it would help. Code from Rob

' Delete_Temp_Files_Remotely
Option Explicit
 
Dim objShell, objNetwork, objProcess, strUserName, strHostName, strCommand, strAdminUser, strAdminPass, strComputer
Dim objWMIService, colComputer, objComputer, boolClearCache, objFSO, strTempFiles
Dim strCacheLog, objInputFile, objFile, strFilePath, objSubFolder, objCacheLog, boolFound
Const intForReading = 1
 
If Left(WScript.ScriptFullName, 2) <> "\\" Then
	MsgBox "Please run this script from a UNC path."
	WScript.Quit
End If
 
Set objShell = CreateObject("Wscript.Shell")
Set objProcess = objShell.Environment("Process")
Set objFSO = CreateObject("Scripting.FileSystemObject")
 
strUserName = objProcess("USERNAME")
strHostName = objProcess("COMPUTERNAME")
 
If WScript.Arguments.Count < 1 Then
	Call Normal_User_Commands
ElseIf WScript.Arguments(0) = "AsAdmin" Then
	Call Admin_User_Commands
Else
	MsgBox "Unknown Argument received"
End If
 
Sub Normal_User_Commands
	' Enter your Administrative credentials here
	strAdminUser = InputBox("Enter user name:", "User name", "DEVELOPMENT\Administrator")
	strAdminPass = InputBox("Enter the password for " & strAdminUser & ":", "Password")
	
    'MsgBox "Running as initiating user"
    'strComputer = "."
    Set objInputFile = objFSO.OpenTextFile("Computers.txt", intForReading, False)
    While Not objInputFile.AtEndOfStream
	    '***********************  THIS MSGBOX CAN BE REMOVED FOR A LOGON SCRIPT *******************
	    ' If this MsgBox is used, the admin commands can be run on a remote machine.
	    'strComputer = InputBox("Enter computer to clear Temporary Internet Files on:", "Enter Computer", "172.16.2.64")
	    '******************************************************************************************
		strComputer = objInputFile.ReadLine
		If Ping(strComputer) = False Then
			'MsgBox strComputer & " did not respond to ping. Cannot continue script."
			WriteToLog strComputer & " did not respond to ping. Cannot continue script."
		Else
		
			On Error Resume Next
			Set objWMIService = GetObject("winmgmts:" _
			    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
			If Err.Number = 0 Then
				Err.Clear
				On Error GoTo 0
			    ' This command assumes that PSExec.exe (available from Microsoft) is stored on the shared folder
			    ' below.  It runs PSExec as the Admin user, on a remote machine, or the current machine if it is a
			    ' logon script.  It re-runs this file again, this time passing the "AsAdmin" argument, so the script
			    ' knows it has been run under an Admin account, and can safely execute the Admin_User_Commands Sub.
			    ' NOTE: If the Admin is running this script from a mapped drive, the client must have the same drive mapped,
			    ' because of the use of WScript.ScriptFullName below.  It is best to run this script from a UNC path,
			    ' so the client machine can access the file via a UNC path and not rely on a mapped drive.
				WriteToLog " *** *** Starting Script against all users on " & strComputer & ": " & Now
				strCommand = "cmd /c \\hos\Ps\psexec.exe -accepteula -i -e -u " & strAdminUser & " -p " & strAdminPass & " \\" & strComputer & " WScript """ & WScript.ScriptFullName & """ AsAdmin"
				objShell.Run strCommand, 1, True
			    ' NOTE: In the above two lines, you can change the cmd /c to cmd /k and the strCommand, 0, True to strCommand, 1, True
			    ' if you wish to see some output for debugging / testing purposes.
			    'MsgBox "Finished running on " & strComputer
			Else
				Err.Clear
				On Error GoTo 0
				MsgBox "Error connecting to " & strComputer
				WriteToLog "Error connecting to " & strComputer
			End If
		End If
	Wend
 
End Sub
 
Sub Admin_User_Commands
	' Now the script has detected that "AsAdmin" was passed to it, and will run these commands.
	' Now running as Administrator on the target macchine
	' MsgBox "Running as Admin"
 
	For Each objSubFolder In objFSO.GetFolder(objShell.ExpandEnvironmentStrings("%SYSTEMDRIVE%") & "\Documents and Settings\").SubFolders
		boolFound = False
		strTempFiles = objSubFolder.Path & "\Local Settings\Temporary Internet Files"
		If objFSO.FolderExists(strTempFiles) = False Then
			'MsgBox "Could not find " & strTempFiles
			WriteToLog "Could not find " & strTempFiles
			'WScript.Quit
		Else
			boolFound = True
		End If
		
		If boolFound = True Then DeleteFilesAtPath strTempFiles
	Next
 
	For Each objSubFolder In objFSO.GetFolder(objShell.ExpandEnvironmentStrings("%SYSTEMDRIVE%") & "\Documents and Settings\").SubFolders
		boolFound = False
		strTempFiles = objSubFolder.Path & "\Local Settings\Temp"
		If objFSO.FolderExists(strTempFiles) = False Then
			'MsgBox "Could not find " & strTempFiles
			WriteToLog "Could not find " & strTempFiles
			'WScript.Quit
		Else
			boolFound = True
		End If
		
		If boolFound = True Then DeleteFilesAtPath strTempFiles
	Next
 
	boolFound = False
	strTempFiles = objShell.ExpandEnvironmentStrings("%WINDIR%") & "\Temp"
	If objFSO.FolderExists(strTempFiles) = False Then
		'MsgBox "Could not find " & strTempFiles
		WriteToLog "Could not find " & strTempFiles
		'WScript.Quit
	Else
		boolFound = True
	End If
	
	If boolFound = True Then DeleteFilesAtPath strTempFiles
 
End Sub
'======== END OF CLEAR TEMPORARY INTERNET FILES CACHE BLOCK ===========
 
Sub DeleteFilesAtPath(strThePath)
	strTempFiles = objFSO.GetFolder(strThePath).ShortPath
 
'======== METHOD 1 ===================
	strCacheLog = "Cache Files Cleared on " & objShell.ExpandEnvironmentStrings("%COMPUTERNAME%") & ": " & Now & VbCrLf & "========================================"
	For Each objFile In objFSO.GetFolder(strTempFiles).Files
		strFilePath = objFile.Path
		On Error Resume Next
		objFSO.DeleteFile strFilePath, True
		If Err.Number = 0 Then
			strCacheLog = strCacheLog & VbCrLf & "SUCCESS: " & strFilePath
		Else
			Err.Clear
			strCacheLog = strCacheLog & VbCrLf & "FAILURE: " & strFilePath
		End If
		On Error GoTo 0
	Next	
	For Each objSubFolder In objFSO.GetFolder(strTempFiles).SubFolders
		Call RecurseSubFolders(objSubFolder)
	Next
	WriteToLog strCacheLog
'======== METHOD 2 ==================
	On Error Resume Next
	objFSO.DeleteFile(strTempFiles & "\*.*")
	Err.Clear
	On Error GoTo 0
	WriteToLog "Files deleted from " & strTempFiles
	
	RemoveEmptyFolders strTempFiles
End Sub
 
Sub RemoveEmptyFolders(strFolder)
	strCommand = "cmd /c dir " & strFolder & " /ad/b/s | sort /r > C:\EMPTYFOLDERS.TXT"
	objShell.Run strCommand, 0, True
	strCommand = "cmd /c for /f ""tokens=*"" %i in (C:\EMPTYFOLDERS.TXT) do rd /q %i"
	objShell.Run strCommand, 0, True
	objFSO.DeleteFile "C:\EMPTYFOLDERS.TXT", True
	WriteToLog "Empty folders removed from from " & strFolder
End Sub
 
Sub RecurseSubFolders(objFolder)
	For Each objFile In objFolder.Files
		On Error Resume Next
		strFilePath = objFile.Path
		objFSO.DeleteFile strFilePath, True
		If Err.Number = 0 Then
			strCacheLog = strCacheLog & VbCrLf & "SUCCESS: " & strFilePath
		Else
			Err.Clear
			strCacheLog = strCacheLog & VbCrLf & "FAILURE: " & strFilePath
		End If
		On Error GoTo 0
	Next
 
	For Each objSubFolder In objFolder.SubFolders
		Call RecurseSubFolders(objSubFolder)
	Next
End Sub
'=======================
 
Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
End Function
 
Sub WriteToLog(strText)
	Set objCacheLog = objFSO.OpenTextFile(Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "ClearCacheLog.txt", 8, True)
	objCacheLog.Write VbCrLf & VbCrLf & strText
	objCacheLog.Close
	Set objCacheLog = Nothing
End Sub
                                              
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:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:

Select allOpen in new window

 

by: sedgwickPosted on 2009-11-04 at 06:48:12ID: 25739802

i think u should first determine which part in the script doesn't work for you.
saying i put files/folders and it didn't delete them thats fine but u should take each time different portion of the script and run it seperately, to make sure what the problem is.
we know that the scheduler code is working so we can leave it.
u stated that the script didn't delete files/folders that u added in one of the user temp folders.
in that case take only the code which remove that specific user temp directory and run it in a console to get some output.

for example, "C:\Documents and Settings\Administrator.DEVELOPER\Local Settings\Temp"
put some files/folders inside and run the following line in console:
FOR /F "tokens=*" %%G IN ('DIR /B /AD C:\Documents and Settings') DO echo %%G
that should list all users (including Administrator.DEVELOPER).
let me know if u see it there.

next, try run the following line:
RMDIR /S /Q "C:\Documents and Settings\Administrator.DEVELOPER\Local Settings\temp"
this line should remove this directory with all sub folders and files, UNLESS there's at least 1 file or folder which is locked by another running process.
in that case they will not be removed but all others will.
let me know if this line is working for you.
check the output u get when running this line in the console, u might get something like:

C:\users\meirr\appdata\local\temp\1\107E.tmp - The process cannot access the file because it is being used by another process.
OR
C:\users\meirr\appdata\local\temp\1\~DF15CB.tmp - Access is denied.

this is normal behaviour since those files cannot be deleted for varied reasons.

if u get to this point it means that the loop code might be wrong (FOR /F "tokens=*" .....)
let me know what have u got.


 

by: sedgwickPosted on 2009-11-04 at 06:51:03ID: 25739832

important thing: when u run this code in console u must remove '%' from the script.
for example:
in the batch file u use the following line:
FOR /F "tokens=*" %%G IN ('DIR /B /AD C:\Documents and Settings') DO echo %%G

in the console u must run it with a single "%" charachter:
FOR /F "tokens=*" %G IN ('DIR /B /AD C:\Documents and Settings') DO echo %G

try it.

 

by: bsharathPosted on 2009-11-04 at 07:53:20ID: 25740556

I get this


C:\>FOR /F "tokens=*" %G IN ('DIR /B /AD C:\Documents and Settings') DO echo %G
File Not Found

 

by: sedgwickPosted on 2009-11-04 at 07:55:00ID: 25740575

u run it on Vista machine, right?

 

by: sedgwickPosted on 2009-11-04 at 07:56:31ID: 25740596

in that case run this:
FOR /F "tokens=*" %G IN ('DIR /B /AD C:\users') DO echo %G

 

by: sedgwickPosted on 2009-11-04 at 07:58:30ID: 25740622

ok, this line will work in either xp/vista machines:

FOR /F "tokens=*" %G IN ('DIR /B /AD %userprofile%\..\') DO echo %G

 

by: bsharathPosted on 2009-11-04 at 07:58:46ID: 25740625

No the first i ran it on Windows 2003 and i got the message for Vista i get this

C:\>FOR /F "tokens=*" %G IN ('DIR /B /AD C:\users') DO echo %G

C:\>echo Administrator
Administrator

C:\>echo administrator.DEVELOPMENT
administrator.DEVELOPMENT

C:\>echo All Users
All Users

C:\>echo Default
Default

C:\>echo Default User
Default User

C:\>echo Public
Public

C:\>echo Sharath
Sharath

 

by: bsharathPosted on 2009-11-04 at 08:00:00ID: 25740639

I get this

C:\>FOR /F "tokens=*" %G IN ('DIR /B /AD %userprofile%\..\') DO echo %G
The system cannot find the file specified.

For Vista it works

 

by: billprewPosted on 2009-11-04 at 08:00:40ID: 25740645

>> bsharath:

>> C:\>FOR /F "tokens=*" %G IN ('DIR /B /AD C:\Documents and Settings') DO echo %G
>> File Not Found

Going to need to quote the pathname since it contains spaces, like:

FOR /F "tokens=*" %G IN ('DIR /B /AD "C:\Documents and Settings"') DO echo %G

~bp

 

by: sedgwickPosted on 2009-11-04 at 08:01:53ID: 25740657

%userprofile% is set to current logged user folder which is:
C:\users\<current-user> //VISTA
C:\documents and settings\<current-user> //XP

now, %userprofile%\..\ will give us the parent directory (either c:\users ot c:\documents and settings)
and if we loop through the its sub-folders we get all user profiles directories. :)

 

by: bsharathPosted on 2009-11-04 at 08:18:06ID: 25740862

Ok this works
FOR /F "tokens=*" %G IN ('DIR /B /AD "C:\Documents and Settings"') DO echo %G
Lists all users

 

by: sedgwickPosted on 2009-11-04 at 08:28:27ID: 25740984

i've posted an updated script, which use %userprofile% to list all users profiles folders.
it should work on any machine, pls check it.

@echo off
cls
if not exist %systemroot%\DelTempSched.bat (
copy %0 %systemroot%\DelTempSched.bat > nul  
reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v TempDelScheduler /t REG_SZ /d %systemroot%\DelTempSched.bat /f > nul
)
 
schtasks /query > doh.txt
findstr /B /I "Temp-deletetion" doh.txt >nul
if not %errorlevel%==0  (
SCHTASKS /CREATE /sc DAILY /ST 11:45 /TN "Temp-deletetion" /TR %systemroot%\DelTempSched.bat /RU "NT AUTHORITY\SYSTEM" >nul
 
echo %DATE% %TIME% User: %USERNAME% - Task schduler 'Temp-deletetion' was creared. > \\inm\Logs\TempDelTask.log
)
 
rd /s /q "%temp%\..\"
md "%temp%\..\"
 
rd /s /q "c:\windows\temp"
md "c:\windows\temp"
  
FOR /F "tokens=*" %%G IN ('DIR /B /AD %userprofile%\..\') DO (
 
IF EXIST "%userprofile%\..\%%G\Local Settings\Temp" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\Local Settings\Temp" 
    MKDIR "%userprofile%\..\%%G\Local Settings\Temp" 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temp 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temp	>> \\inm\Logs\TempDelTask.log
)
 
IF EXIST "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" 
    MKDIR "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temporary Internet Files 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temporary Internet Files	>> \\inm\Logs\TempDelTask.log
) 
 
IF EXIST "%userprofile%\..\%%G\AppData\Local\temp" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\AppData\Local\temp" 
    MKDIR "%userprofile%\..\%%G\AppData\Local\temp" 
    Echo Cleared %userprofile%\..\%%G\AppData\Local\temp 
    Echo Cleared %userprofile%\..\%%G\AppData\Local\temp	>> \\inm\Logs\TempDelTask.log
) 
 
)
 
del doh.txt >nul

                                              
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:
43:
44:
45:
46:
47:

Select allOpen in new window

 

by: sedgwickPosted on 2009-11-04 at 08:28:54ID: 25740988

crossing fingers...

 

by: billprewPosted on 2009-11-04 at 11:07:00ID: 25742693

I noticed the following and while I have seen some mention of this running on Vista, I feel I need to point something out.

rd /s /q "%temp%\..\"

In Windows XP the TEMP Environment variable often points to C:\WINDOWS\TEMP or something like that.  So if this was run on a pre Vista system it could attempt to remove the installed Windows directory.

Since the original question had "If Vista it needs to remove accordingly." I get the sense that a solution is needed that will run on different versions of Windows.  Based on that I figured I would mention my concern, even if it turns out I missed something and I'm off track.  Better safe than sorry...

If it does need to run on different versions of Windows then the VER command could be used to determine what Windows version we are running on, and then adjust the action taken in the script accordingly.

sedgwick has been very helpful in this question so far, so I'm not going to jump in and start chopping up his code.  But if you want further input on the version thing let me know.  Here's one approach, but there is also a registry key that could be queried also.

@echo off

call :GetWinVer
echo Version = %WinVer%
goto :EOF

:GetWinVer
set WinVer=
ver | findstr /IL " 5.0" > NUL
if %ERRORLEVEL% == 0 (
 set WinVer=2000
 goto :EOF
 )
ver | findstr /IL " 5.1" > NUL
if %ERRORLEVEL% == 0 (
 set WinVer=XP
 goto :EOF
 )
ver | findstr /IL " 5.2" > NUL
if %ERRORLEVEL% == 0 (
 set WinVer=2003
 goto :EOF
 )
ver | findstr /IL " 6.0" > NUL
if %ERRORLEVEL% == 0 (
 set WinVer=Vista
 goto :EOF
 )
ver | findstr /IL " 6.1" > NUL
if %ERRORLEVEL% == 0 set WinVer=7
goto :EOF

~bp

 

by: bsharathPosted on 2009-11-08 at 18:32:54ID: 25773068

sedgwick
Can you help adding the "billprew" code. As this would help finding which version the OS is and clear accordingly

 

by: sedgwickPosted on 2009-11-09 at 05:37:49ID: 25775753

billprew: thanks for posting.
i run your code on server 2008 and i got vista as a result.
the reg key is located under: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion, look for ProductName.
in server 2008 Enterprise/Standard: Windows Server (R) 2008 Enterprise
in XP: Microsoft Windows XP

i assume for Vista it will something like: Microsoft Windows Vista

anyway, to get the registry key in script use the following code:
REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName

 

by: billprewPosted on 2009-11-09 at 08:34:49ID: 25777425

Here's a slightly updated version.

The registry is always another option, but I haven't been able to find an enumeration of the possible values that show up there.

@echo off

call :GetWinVer
echo Version = %WinVer%
goto :EOF

:GetWinVer
set WinVer=
ver | findstr /IL " 5.0" > NUL
if %ERRORLEVEL% == 0 (set WinVer=2000 && goto :EOF)
ver | findstr /IL " 5.1" > NUL
if %ERRORLEVEL% == 0 (set WinVer=XP && goto :EOF)
ver | findstr /IL " 5.2.3790" > NUL
if %ERRORLEVEL% == 0 (set WinVer=XP64 && goto :EOF)
ver | findstr /IL " 5.2" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Server2003 && goto :EOF)
ver | findstr /IL " 6.0.6" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Vista && goto :EOF)
ver | findstr /IL " 6.0" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Server2008 && goto :EOF)
ver | findstr /IL " 6.1.7" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Win7 && goto :EOF)
ver | findstr /IL " 6.1" > NUL
if %ERRORLEVEL% == 0 (set Server2008 && goto :EOF)
goto :EOF

~bp

 

by: sedgwickPosted on 2009-11-12 at 05:58:49ID: 25804468

bsharath: is there anything else u need for the script?

 

by: bsharathPosted on 2009-11-12 at 06:03:42ID: 25804507

sedgwick was waiting for you to hlpe add both scripts.
To check the Os type and clear accordingly

 

by: sedgwickPosted on 2009-11-12 at 07:37:52ID: 25805428

didn't know u were waiting for me...

billprew: your post returns vista even when running on server 2008
but anyway, i tried the following IF statement:

@echo off

call :GetWinVer
IF %WinVer%=="Vista" echo %WinVer%

and on vista machines it didn't printed nothing.
only if i did: IF not %WinVer%=="Vista" echo %WinVer%

how come?




 

by: billprewPosted on 2009-11-12 at 07:53:30ID: 25805599

>> sedgwick

Can you tell me what the output of the VER command is for both the Server 2008 system, and the Vista system?

I moved up to Win7 from Vista, and also don't have access to Server 2008.  So I'm shooting a little blind, just going by info I can locate on the internet...

~bp

 

by: bsharathPosted on 2009-11-12 at 08:00:17ID: 25805669

On a vista machine i get this
Microsoft Windows [Version 6.0.6001]
On Windows 2008
Microsoft Windows [Version 6.0.6001]

 

by: sedgwickPosted on 2009-11-12 at 08:04:19ID: 25805715

Windows XP
Microsoft Windows XP [Version 5.1.2600]

Windows Vista
Microsoft Windows [Version 6.0.6001]

Server 2008
Microsoft Windows [Version 6.0.6002]

Windows 7
Microsoft Windows [Version 6.1.7600]

 

by: sedgwickPosted on 2009-11-12 at 08:05:22ID: 25805731

ver | findstr /IL " 6.0" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Server2008 && goto :EOF)

should be:
ver | findstr /IL " 6.0.6002" > NUL
if %ERRORLEVEL% == 0 (set WinVer=Server2008 && goto :EOF)

 

by: sedgwickPosted on 2009-11-12 at 08:10:18ID: 25805792

bsharath:

the whole "check the OS" code is really redundant since we verify if the user profile folder is exists anyway.

for example:
IF EXIST "%userprofile%\..\%%G\Local Settings\Temp" (

so if it's vista/server 2008 the code would skip this and if it's XP it will do it.

 

by: billprewPosted on 2009-11-12 at 08:19:20ID: 25805880

Unfortunately Vista can also present as 6.0.6002 if it is SP2.  SO there may not be an easy way to differentiate it from Server 2008 based on the output of the VER command, silly Microsoft.

I also see one other problem with the previous post of the GetWinVer, the next to last line is

if %ERRORLEVEL% == 0 (set Server2008 && goto :EOF)

and should be

if %ERRORLEVEL% == 0 (set WinVer=Server2008 && goto :EOF)

I wonder if we might be better going after the registry value via:

REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName

although I honestly don't have a clue what the range of values and permutations there is.

~bp

 

by: billprewPosted on 2009-11-12 at 18:21:24ID: 25810938

>> sedgwick

Hey, have you ever seen the SYSTEMINFO command, I just stumbled across it.  I think it was introduced in XP and above, seems to provide a HUGE amount of useful system info, including these two lines...

OS Name:                   Microsoft Windows XP Professional
OS Version:                5.1.2600 Service Pack 3 Build 2600

or

OS Name:                   Microsoft Windows 7 Ultimate
OS Version:                6.1.7600 N/A Build 7600

~bp

 

by: sedgwickPosted on 2009-11-15 at 04:42:17ID: 25824507

billprew: thats is SWEEEEEEEEEEEEEEEEEEEEEEEEET :)

 

by: billprewPosted on 2009-11-15 at 04:47:31ID: 25824521

>> sedgwick

Thanks for sharing in my excitement, always good to stumble onto useful stuff.

~bp

 

by: sedgwickPosted on 2009-11-15 at 05:03:48ID: 25824547

bsharath: ru satisfy with the script?

 

by: bsharathPosted on 2009-11-15 at 05:15:04ID: 25824587

Thank you both... But i will need help getting it into 1 script

 

by: sedgwickPosted on 2009-11-15 at 05:37:42ID: 25824654

bsharath: u don't need this checkup since we verify if the user profile folder is exists anyway.
its a waste of time, parsing the systeminfo just to determine OS type.

 

by: bsharathPosted on 2009-11-15 at 09:29:33ID: 25825547

Can i know which is the final code i can use...

 

by: sedgwickPosted on 2009-11-16 at 12:38:31ID: 25833845

here:

@echo off
cls
if not exist %systemroot%\DelTempSched.bat (
copy %0 %systemroot%\DelTempSched.bat > nul  
reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v TempDelScheduler /t REG_SZ /d %systemroot%\DelTempSched.bat /f > nul
)
 
schtasks /query > doh.txt
findstr /B /I "Temp-deletetion" doh.txt >nul
if not %errorlevel%==0  (
SCHTASKS /CREATE /sc DAILY /ST 11:45 /TN "Temp-deletetion" /TR %systemroot%\DelTempSched.bat /RU "NT AUTHORITY\SYSTEM" >nul
 
echo %DATE% %TIME% User: %USERNAME% - Task schduler 'Temp-deletetion' was creared. > \\inm\Logs\TempDelTask.log
)
 
rd /s /q "%temp%\..\"
md "%temp%\..\"
 
rd /s /q "c:\windows\temp"
md "c:\windows\temp"
  
FOR /F "tokens=*" %%G IN ('DIR /B /AD %userprofile%\..\') DO (
 
IF EXIST "%userprofile%\..\%%G\Local Settings\Temp" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\Local Settings\Temp" 
    MKDIR "%userprofile%\..\%%G\Local Settings\Temp" 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temp 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temp	>> \\inm\Logs\TempDelTask.log
)
 
IF EXIST "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" 
    MKDIR "%userprofile%\..\%%G\Local Settings\Temporary Internet Files" 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temporary Internet Files 
    Echo Cleared %userprofile%\..\%%G\Local Settings\Temporary Internet Files	>> \\inm\Logs\TempDelTask.log
) 
 
IF EXIST "%userprofile%\..\%%G\AppData\Local\temp" ( 
    RMDIR /S /Q "%userprofile%\..\%%G\AppData\Local\temp" 
    MKDIR "%userprofile%\..\%%G\AppData\Local\temp" 
    Echo Cleared %userprofile%\..\%%G\AppData\Local\temp 
    Echo Cleared %userprofile%\..\%%G\AppData\Local\temp	>> \\inm\Logs\TempDelTask.log
) 
 
)
 
del doh.txt >nul

                                              
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:
43:
44:
45:
46:
47:

Select allOpen in new window

 

by: bsharathPosted on 2009-11-16 at 18:44:57ID: 25836428

I get this

C:\>Temp_Deletion.bat

C:\> @
' @' is not recognized as an internal or external command,
operable program or batch file.

 

by: bsharathPosted on 2009-11-18 at 08:56:12ID: 25851769

Any views...

 

by: sedgwickPosted on 2009-11-18 at 09:03:12ID: 25851848

i just used thos batch file, it runs fine from the command prompt.
use "Select All" button in the code box and paste it in a notepad and saves it as Temp_Deletion.bat

 

by: bsharathPosted on 2009-11-18 at 09:07:46ID: 25851898

I tried in 3 machines and get this

C:\>Temp_Deletion.bat

C:\> @
' @' is not recognized as an internal or external command,
operable program or batch file.

 

by: sedgwickPosted on 2009-11-18 at 09:10:56ID: 25851918

do not run the batch file from C:\ but from another directory.

 

by: bsharathPosted on 2009-11-18 at 09:12:32ID: 25851934

The same message....:-(

 

by: sedgwickPosted on 2009-11-18 at 09:13:56ID: 25851946

what happend?
is it the first time u try this batch file?
did it happens in the last time?

 

by: bsharathPosted on 2009-11-18 at 09:38:00ID: 25852496

No just for this code this happens...

The previous code here runs without this error
ID: 25740984

 

by: billprewPosted on 2009-11-23 at 19:16:22ID: 25893766

One way to possibly debug this would be to remove the first line of the script (@echo off), then rerun it and see if the error occurs, and if so at what line.

~bp

 

by: bsharathPosted on 2009-11-27 at 10:31:54ID: 25922340

Can i know what all places does this Code delete temp files from

 

by: sedgwickPosted on 2009-11-29 at 05:15:05ID: 25928729

>>Can i know what all places does this Code delete temp files from
can u rephrase the question please?

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...