Reputation: 63
I was trying to write a code to check for a specific file if it is existing in a folder and subfolder in any subfolder \DESKTOP in c:\users*.* (= all users directories). And if the file is existing in any folder the script will delete the file.
Option Explicit
Dim Shell, FSO, DesktopPath
Dim objShortcutFile, objDesktopFolder, objDesktopSubFolder, Folder, strSysDrive
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
strSysDrive = Shell.ExpandEnvironmentStrings("%SystemDrive%")
Set Folder = FSO.GetFolder(strSysDrive & "\Users")
msgbox Folder & "\sample1.lnk"
For Each objDesktopFolder in Folder.SubFolders
If FSO.FileExists(Folder & "\sample1.lnk") Then
FSO.DeleteFile Folder & "\sample1.lnk"
msgbox "success"
Else
msgbox "not existing"
End If
Next
Upvotes: 0
Views: 3705
Reputation: 8572
Folder
is the C:\Users
folder object; objDesktopFolder
is the folder object for each folder directly in C:\Users
, e.g. C:\Users\user1 - not further levels of subfolders e.g. C:\Users\user1\Desktop (so it's a misleading name as it is not the desktop folder).
If you only want to look directly on the desktop, then just change this line (and any other line that uses that path):
If FSO.FileExists(Folder & "\sample1.lnk") Then
to:
If FSO.FileExists(FSO.BuildPath(objDesktopFolder.Path, "Desktop\sample1.lnk")) Then
If you also want to look through each folder that may exist on the desktop, then you'll have to perform the same sort of logic, e.g.
Option Explicit
Dim Shell, FSO, DesktopPath
Dim objShortcutFile, objDesktopFolder, objDesktopSubFolder, Folder, strSysDrive
Dim filepath, userfolder, desktop, subfolder, filename
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
strSysDrive = Shell.ExpandEnvironmentStrings("%SystemDrive%")
Set Folder = FSO.GetFolder(strSysDrive & "\Users")
msgbox Folder & "\sample1.lnk"
filename = "sample1.lnk"
For Each userfolder in Folder.SubFolders
desktop = FSO.BuildPath(userfolder.Path, "Desktop")
filepath = FSO.BuildPath(desktop, filename)
If FSO.FolderExists(desktop) Then
' Delete file on desktop
If FSO.FileExists(filepath) Then
FSO.DeleteFile filepath, True
MsgBox "Success: deleted " & filepath
Else
MsgBox filepath & " doesn't exist"
End If
' Check folders on desktop
For Each subfolder In FSO.GetFolder(desktop).SubFolders
filepath = FSO.BuildPath(subfolder.Path, filename)
If FSO.FileExists(filepath) Then
FSO.DeleteFile filepath, True
MsgBox "Success: deleted " & filepath
End If
Next
End If
Next
That will only look for the file in folders directly on the desktop (as well as the file on the desktop, of course). If you want to look through further levels of subfolders then it's really best to create a separate sub that uses recursion to go through all levels of subfolders.
Upvotes: 1