检查并删除文件夹和子文件夹中的特定文件

时间:2014-10-31 15:41:29

标签: search vbscript directory delete-file subdirectory

我试图编写一个代码来检查特定文件,如果它存在于c:\ users *。*(=所有用户目录)中任何子文件夹\ DESKTOP中的文件夹和子文件夹中。如果文件存在于任何文件夹中,则脚本将删除该文件。

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

1 个答案:

答案 0 :(得分:1)

FolderC:\Users文件夹对象; objDesktopFolder是直接在C:\Users中的每个文件夹的文件夹对象,例如C:\ Users \ user1 - 不是更高级别的子文件夹,例如C:\ Users \ user1 \ Desktop(所以这是一个误导性的名称,因为它不是桌面文件夹)。

如果您只想直接查看桌面,则只需更改此行(以及使用该路径的任何其他行): If FSO.FileExists(Folder & "\sample1.lnk") Then

于: If FSO.FileExists(FSO.BuildPath(objDesktopFolder.Path, "Desktop\sample1.lnk")) Then

如果您还想查看桌面上可能存在的每个文件夹,那么您必须执行相同类型的逻辑,例如

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

这只会直接在桌面上查找文件夹中的文件(当然还有桌面上的文件)。如果你想查看更多级别的子文件夹,那么最好创建一个单独的sub,它使用递归来遍历所有级别的子文件夹。