VBScript to search for and delete file
Hi, I have a file (say "normal.dot") that may be under any user in c:\Documents and Settings. I am looking for a script that searches for this file and then deletes it.
I have searched the web but can't find one. Any ideas?
Thanks,
Mike.
I have searched the web but can't find one. Any ideas?
Thanks,
Mike.
0 Comments
[ + ] Show comments
Answers (28)
Please log in to answer
Posted by:
spartacus
18 years ago
Perhaps worth noting that there may be some folders where you might not wish to delete the normal.dot file from (e.g. Default User profile (?))
With this in mind, the following VB Script uses an exemptions list to bypass any folders you wish to preserve the file in :
Hope this is of some use [:)]
Regards,
Spartacus
With this in mind, the following VB Script uses an exemptions list to bypass any folders you wish to preserve the file in :
' Sample VB Script to remove a designated file (default is NORMAL.DOT) located in the profile folder for every user on the
' system. There is provision for exempting certain folders via the constant ProtectedUsers which is set to a comma separated
' list which can be altered according to your requirements
'
' You should alter constant DeleteProtectedUsers from FALSE to TRUE to delete *ALL* copies of the file regardless of profile
'
Const FileToDelete = "Normal.DOT"
Const AllUsers = "\All Users"
Const DeleteProtectedUsers = "FALSE"
Const TemplatesFolder = "Application Data\Microsoft\Templates"
Const ProtectedUsers = "Default User,Administrator,All Users,NetworkService,LocalService"
Dim oFSO, oWSH
Dim sAllUsersProfile, oAllUsersFolder, sProfilesRoot, oFolder
Dim colFSOSubFolders
Dim protuserarray
Dim DeleteFlag
On Error Resume Next ' this is set because the designated file may be locked from deletion
protuserarray = Split(ProtectedUsers,",")
' Instantiate the objects
Set oFSO = CreateObject("Scripting.FileSystemObject")
set oWSH = CreateObject("WScript.Shell")
' Get the Allusers profile folder path first and from this determine profiles parent folder
'
sAllUsersProfile = oWSH.ExpandEnvironmentStrings("%ALLUSERSPROFILE%")
Set oAllUsersFolder = oFSO.GetFolder(sAllUsersProfile)
sProfilesRoot = oAllUsersFOlder.ParentFolder
' Now enumerate all existing user profile folders
Set oFolder = oFSO.GetFolder(sProfilesRoot)
Set colFSOSubfolders = oFolder.Subfolders
' Now go through each existing user profile folder looking for the designated file to delete
For Each objSubfolder in colFSOSubfolders
DeleteFlag = "TRUE"
if oFSO.FileExists(sProfilesRoot & "\" & objSubfolder.Name & "\" & TemplatesFolder & "\" & FileToDelete) then
' Found the file, now establish whether containing folder is on the exempt list
if NOT DeleteProtectedUsers then
For Each element in protuserarray
if ucase(element) = ucase(objSubfolder.Name) then
DeleteFlag = "FALSE" ' mark this occurrence of the designated file as exempt from deletion
exit for
end if
Next
end if
If DeleteFlag then
' File was found in a folder that is not exempt, so go ahead and attempt to delete
oFSO.DeleteFile sProfilesRoot & "\" & objSubfolder.Name & "\" & TemplatesFolder & "\" & FileToDelete,TRUE
end if
end if
Next
' Clean up before exiting
set oFSO = Nothing
set oWSH = Nothing
Hope this is of some use [:)]
Regards,
Spartacus
Posted by:
jimmy.alappatt
18 years ago
Use this script after the installfinalize sequence and will forcefully delete the file.
for testing purposes, i have kept the file name as jimmy.dot which has to be renamed as per the requirement.
important note: all the files with the same name which is present in any folder inside the c:\Documents and settings will be deleted.
'==========================================================================
Option Explicit
On Error Resume Next
'==========================================================================
'
' DESCRIPTION: To append the environment variable.
'
' NAME: delete_folder.vbs
'
'
' AUTHOR: Jimmy Antony
' DATE: 01/10/2006
' USAGE: To delete the file "jimmy.dot" which is present any where in C:\Documents and Settings
'
' SEQUENCE: After installfinalize
'
'
' NOTE: This script will remove the folder forcefully
'
'==========================================================================
ShowFolderList("C:\Documents and Settings")
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
ShowFolderList(f1.path)
ShowFileList(f1.path)
Next
End Function
Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
if strcomp(f1.name,"jimmy.dot") = 0 then
fso.deletefile f1.path, true
Exit For
Exit Function
end if
Next
End Function
for testing purposes, i have kept the file name as jimmy.dot which has to be renamed as per the requirement.
important note: all the files with the same name which is present in any folder inside the c:\Documents and settings will be deleted.
'==========================================================================
Option Explicit
On Error Resume Next
'==========================================================================
'
' DESCRIPTION: To append the environment variable.
'
' NAME: delete_folder.vbs
'
'
' AUTHOR: Jimmy Antony
' DATE: 01/10/2006
' USAGE: To delete the file "jimmy.dot" which is present any where in C:\Documents and Settings
'
' SEQUENCE: After installfinalize
'
'
' NOTE: This script will remove the folder forcefully
'
'==========================================================================
ShowFolderList("C:\Documents and Settings")
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
ShowFolderList(f1.path)
ShowFileList(f1.path)
Next
End Function
Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
if strcomp(f1.name,"jimmy.dot") = 0 then
fso.deletefile f1.path, true
Exit For
Exit Function
end if
Next
End Function
Posted by:
brenthunter2005
18 years ago
Posted by:
Meic
18 years ago
Posted by:
Meic
18 years ago
Posted by:
spartacus
18 years ago
As it stands, the script I posted will search for and delete the NORMAL.DOT file in every users profile located in the Application Data\Microsoft\Templates folder. This should work for every user having a profile folder under C:\Documents and Settings.
However I made an exception for the following "special" case profiles -
Default User,
Administrator,
All Users,
NetworkService,
LocalService
(the last two probably won't contain a normal.dot, in any case, but there you go)
If you want an outright deletion of *all* normal.dot files from
Application Data\Microsoft\Templates then alter the following line in the script :
Const DeleteProtectedUsers = "FALSE"
to
Const DeleteProtectedUsers = "TRUE"
If your Templates path differs from Application Data\Microsoft\Templates then you can alter the following line :
Const TemplatesFolder = "Application Data\Microsoft\Templates" to meet your own particular needs.
Regards,
Spartacus
However I made an exception for the following "special" case profiles -
Default User,
Administrator,
All Users,
NetworkService,
LocalService
(the last two probably won't contain a normal.dot, in any case, but there you go)
If you want an outright deletion of *all* normal.dot files from
Application Data\Microsoft\Templates then alter the following line in the script :
Const DeleteProtectedUsers = "FALSE"
to
Const DeleteProtectedUsers = "TRUE"
If your Templates path differs from Application Data\Microsoft\Templates then you can alter the following line :
Const TemplatesFolder = "Application Data\Microsoft\Templates" to meet your own particular needs.
Regards,
Spartacus
Posted by:
anonymous_9363
15 years ago
Posted by:
toonwolf
14 years ago
I would like to run this at logon and instead of searching for files in all profiles I would only like to search and delete files in the profile of the user logging on. IE: Replace
I know I need to declare this variable with:
ShowFolderList("C:\Documents and Settings")
with ShowFolderList(%USERPROFILE%)
I know I need to declare this variable with:
Set oShell = CreateObject("Wscript.Shell")
strUserProfile = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
but I can't seem to make it work.
Posted by:
anonymous_9363
14 years ago
Nice and informative. Is that what you say when you take your car into the garage: "It doesn't work"? :)
What doesn't work? Is it that nothing is returned in strUserProfile? Or the is it the deletion which fails? As I said on another AppDeploy forum today, we're good, but fall somewhat short in our psychic abilities.
What doesn't work? Is it that nothing is returned in strUserProfile? Or the is it the deletion which fails? As I said on another AppDeploy forum today, we're good, but fall somewhat short in our psychic abilities.
Posted by:
toonwolf
14 years ago
Sorry for not being more specific. What I'm trying to acheive is instead of searching through all profiles and delete the files I would like this script to run at logon, and only to check and delete files in the logged on user's profile. I know it's possible to use environment variables in vbscript, but I'm not sure how to use them.
I've tried to modify the script posted by Jimmy Antony above, but the file is not deleted. (BTW: I've tested the script above with C:\Documents and settings hardcoded and that's working ok) This is how my modified script looks like:
I've tried to modify the script posted by Jimmy Antony above, but the file is not deleted. (BTW: I've tested the script above with C:\Documents and settings hardcoded and that's working ok) This is how my modified script looks like:
'==========================================================================
Option Explicit
On Error Resume Next
'==========================================================================
'
' DESCRIPTION: To append the environment variable.
'
' NAME: delete_folder.vbs
'
'
' AUTHOR: Jimmy Antony
' DATE: 01/10/2006
' USAGE: To delete the file "jimmy.dot" which is present any where in C:\Documents and Settings
'
' SEQUENCE: After installfinalize
'
'
' NOTE: This script will remove the folder forcefully
'
'==========================================================================
' This is where I declare the environment variable
Set oShell = CreateObject("Wscript.Shell")
strUserProfile = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
' ShowFolderList("C:\Documents and Settings")
' Replaced hardcoded path with enviroment variable but the syntax must be wrong I think
ShowFolderList(%USERPROFILE%)
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
ShowFolderList(f1.path)
ShowFileList(f1.path)
Next
End Function
Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
if strcomp(f1.name,"mytestfile.txt") = 0 then
fso.deletefile f1.path, true
Exit For
Exit Function
end if
Next
End Function
Posted by:
toonwolf
14 years ago
I'm answering my own question here as I managed to get it working using the following code:
'==========================================================================
' Option Explicit
On Error Resume Next
'==========================================================================
'
' Script to search and delete files only inside the logged on users profile.
' Define the files you need to delete in objDic.Add LCase lines
' Run this when a user log on and they will in fact delete their own files!
' Based on Jimmy Antony's script
'
'==========================================================================
Dim objDic
Dim oShell
Set objDic = CreateObject("Scripting.Dictionary")
' Define the files you need to delete
objDic.Add LCase("file1.txt"), ""
objDic.Add LCase("file2.txt"), ""
objDic.Add LCase("shortcut1.lnk"), ""
Set oShell = CreateObject("Wscript.Shell")
strUserProfile = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
' This is where it will only search and delete in the logged on users profile
ShowFolderList(strUserProfile)
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
ShowFolderList(f1.path)
ShowFileList(f1.path)
Next
End Function
Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
if objDic.Exists(LCase(f1.name)) then
fso.deletefile f1.path, true
end if
Next
End Function
Posted by:
imonwifi
14 years ago
Hey Guys i am looking for VB script that can look for particular file type lets says *.dat file could be anywhere in Drive E;
I would like to zip this file if its older then 3 days and then delete the original one.
would like to use this script to save space issues on drive.
Can anyone Help?
Jimmy or anyone can you Help?
I would like to zip this file if its older then 3 days and then delete the original one.
would like to use this script to save space issues on drive.
Can anyone Help?
Jimmy or anyone can you Help?
Posted by:
anonymous_9363
14 years ago
Posted by:
AngelD
14 years ago
You'll have to add your own error trapping and compression/deletion verification.
Dim strSearchInDrive, strSearchForFileExtension, intCompressFilesOlderThenDays
strSearchInDrive = "E:"
strSearchForFileExtension = "dat"
intCompressFilesOlderThenDays = 3
CompressFilesWithExtensionOlderThenDays strSearchInDrive, strSearchForFileExtension, intCompressFilesOlderThenDays
'// source: http://blogs.technet.com/heyscriptingguy/archive/2006/02/03/how-can-i-search-for-multiple-file-extensions-in-a-single-wql-query.aspx
'// source: http://www.informit.com/articles/article.aspx?p=23751
Sub CompressFilesWithExtensionOlderThenDays(ByVal inDrive, ByVal fileExtension, ByVal olderThenDays)
Dim strComputer, objWMIService, colFiles, objFile
Dim FileDate, FileDaysOld
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_Datafile Where Extension = '" & fileExtension & "' AND Drive = '" & inDrive & "'")
For Each objFile in colFiles
FileDate = WMIDateStringToDate(objFile.LastModified) '// convert WMI date string to Date
FileDaysOld = CInt(Mid(DiffADate(FileDate), 2)) '// get positiv number of negative string
If FileDaysOld > olderThenDays Then
'WScript.Echo "(" & FileDaysOld & " days old) " & objFile.Name
'WScript.Echo "Compress to: " & objFile.Drive & objFile.Path & "\" & objFile.FileName & ".zip"
Call ZipFile(objFile.Name, objFile.Drive & objFile.Path & "\" & objFile.FileName & ".zip")
'WScript.Echo "Deleting: " & objFile.Name
Call DeleteFile(objFile.Name, True)
End If
Next
End Sub
'// source: http://msdn.microsoft.com/en-us/library/xhtyw595(VS.85).aspx
Function DiffADate(ByVal theDate)
Const vbGeneralDate = 0
theDate = FormatDateTime(theDate, vbGeneralDate)
DiffADate = DateDiff("d", Now, theDate)
End Function
'// source: http://technet.microsoft.com/en-us/library/ee156576.aspx
Function WMIDateStringToDate(ByVal dtmInstallDate)
WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
Mid(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
& " " & Mid (dtmInstallDate, 9, 2) & ":" & _
Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, 13, 2))
End Function
'// source: http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_24128934.html
Function ZipFile(ByVal strSource, ByVal strTarget)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim file, shl
set fso = CreateObject("Scripting.FileSystemObject")
'write zip file header
set file = fso.opentextfile(strTarget, ForWriting, true)
file.write "PK" & chr(5) & chr(6) & string(18,chr(0))
file.close
'copy source file to zip file
set shl = CreateObject("Shell.Application")
shl.namespace(strTarget).copyhere(strSource)
do until shl.namespace(strTarget).items.count = 1
wscript.sleep 1000
loop
set shl = nothing
set fso = nothing
End Function
'// source: http://msdn.microsoft.com/en-us/library/thx0f315(VS.85).aspx
Sub DeleteFile(ByVal filePath, ByVal forceRemoval)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Call fso.DeleteFile(filePath, forceRemoval)
Set fso = Nothing
End Sub
Posted by:
notice
14 years ago
Hi, I have a directory call "dirname" under c:\ directory. Under "dirname" directory i have different directories like "default" "vi11" "vi22" "vi33" "vi44" "vi55".
I am looking for a script that remove all directories that begin with "vi" without removing "default" directory.
Any ideas?
Thanks,
Jose
I am looking for a script that remove all directories that begin with "vi" without removing "default" directory.
Any ideas?
Thanks,
Jose
Posted by:
stabish
14 years ago
Thank You Spartacus for the script it really helped. So if i was to delete the "Normal.DOT" from LocalAppData folder as well should i write another script & change the following values or can we add something to the existing script?
Const TemplatesFolder = "Application Data\Microsoft\Templates" TO
Const TemplatesFolder = "Local Settings\Application Data\Microsoft\Templates"
Const TemplatesFolder = "Application Data\Microsoft\Templates" TO
Const TemplatesFolder = "Local Settings\Application Data\Microsoft\Templates"
Posted by:
anonymous_9363
14 years ago
No, that's the amateur's way. Edit the code so that the work is done inside a function (use a Function rather than a Sub, so that you can return a value, Success or Failure). Then pass the folder name and file spec into the function as separate parameters. Remember - as ever - to error-trap everything, e.g. does the path passed in exist; does the file exist, did the file actually get deleted and so on. Assume NOTHING, other than that everything will go wrong.
Posted by:
honestgoofy
13 years ago
Posted by:
anonymous_9363
13 years ago
Posted by:
RobSheppard
13 years ago
Hello there,
I just wanted to drop by and say thanks to all, but in particular to spartacus for the info/code on this thread. Using this as a start, I was able to modify it for my own purposes and do something that's been bugging me for ages. I thought it was only fair and decent to at least say thanks for the original vbscript.
-Rob
I just wanted to drop by and say thanks to all, but in particular to spartacus for the info/code on this thread. Using this as a start, I was able to modify it for my own purposes and do something that's been bugging me for ages. I thought it was only fair and decent to at least say thanks for the original vbscript.
-Rob
Posted by:
athertonwj
13 years ago
Hi folks,
I am looking for a script that will find ALL instances of an .exe file (e.g., test.exe) on the machine AND shared drives and delete it. I have been trying to use the aforementioned pieces, modified, but I'm relatively new to this and haven't been able to spend as much time on scripting as I'd like to. Consequently, I have a hard time figuring out the logic. Anyhoo, if you can help, I'd greatly appreciate it; need to get a particular file basically out of our environment as it is messing up our printer scripts.
Thanks and enjoy the day!
Bill
I am looking for a script that will find ALL instances of an .exe file (e.g., test.exe) on the machine AND shared drives and delete it. I have been trying to use the aforementioned pieces, modified, but I'm relatively new to this and haven't been able to spend as much time on scripting as I'd like to. Consequently, I have a hard time figuring out the logic. Anyhoo, if you can help, I'd greatly appreciate it; need to get a particular file basically out of our environment as it is messing up our printer scripts.
Thanks and enjoy the day!
Bill
Posted by:
athertonwj
13 years ago
In regards to my original query, I have now gotten my script to find all instances of the "gadgetman.exe" file anywhere on the local machine, however, it only deletes the file from C:\, not the other instances in various places below this. Any ideas on how to modify this to complete the "search and destroy" off all instances locally and on a user's shared drive (s)?
Thanks, and enjoy the day, All!
Bill
This is what I have, pieced together from various scripts, pretty much none of it mine:
Const DeleteReadOnly = True
'Set oFSO = CreateObject("Scripting.FileSystemObject") (commented out because I didn;t see it helpinig, but needed to try it; wasn't sure what I was doing, as initially styated)
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWshShell = CreateObject("WScript.Shell")
sDir = oWshShell.ExpandEnvironmentStrings("%temp%\dir.txt")
sFileName = "\gadgetman.exe"
If oFSO.FileExists(sDir) Then oFSO.DeleteFile(sDir)
For Each oDrive In oFSO.Drives
if oDrive.DriveType = 2 Then Search oDrive.DriveLetter
Next
Set oFile = oFSO.OpenTextFile(sDir, 1)
aNames = Split(oFile.ReadAll, VbCrLf)
oFile.Close
For Each sName In aNames
If InStr(1, sName, sFileName, 1) > 0 Then WScript.Echo sName
Next
dim filesys
Set filesys = CreateObject("Scripting.FileSystemObject")
filesys.CreateTextFile "\gadgetman.exe", True
If filesys.FileExists("\gadgetman.exe") Then
filesys.DeleteFile "\gadgetman.exe"
Wscript.Echo("File deleted")
End If
Sub Search(sDrive)
WScript.Echo "Scanning drive " & sDrive & ":"
oWshShell.Run "cmd /c dir /s /b " & sDrive & ":\" & sName & " >>" & sDir, 0, True
End Sub
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
Scanning drive C:
C:\Documents and Settings\watherton\gadgetman.exe
C:\Documents and Settings\watherton\My Documents\gadgetman.exe
C:\Users\watherton\gadgetman.exe
C:\Users\watherton\My Documents\gadgetman.exe
File deleted
Exit code: 0 , 0000h
Rating comments in this legacy AppDeploy message board thread won't reorder them,
so that the conversation will remain readable.
so that the conversation will remain readable.