在vbs腳本中排除資料夾

在vbs腳本中排除資料夾

我有一個 VBS 腳本,可以刪除開始功能表中的所有內容,然後從頭開始重新新增。我將其用作網域中的登入腳本。但上週我意識到有些人使用不同的應用程序,並且這些應用程式不在中央共享上,所以我的問題是是否可以從該腳本中排除某些資料夾以刪除

Dim objShell, strCmd, intRunError, strFolder, objFileSys

Set objShell = CreateObject( "WScript.Shell" )
appDataLocation=objShell.ExpandEnvironmentStrings("%APPDATA%")


Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(appDataLocation & "\Microsoft\Windows\Start Menu\Programs")

' delete all subfolders and files
For Each f In folder.SubFolders
   On Error Resume Next
   name = f.name
   f.Delete True
Next

' delete all files in root folder
for each f in folder.Files
   On Error Resume Next
   name = f.name
   f.Delete True
Next

Set objFileSys = CreateObject("Scripting.FileSystemObject")
objFileSys.GetFolder("\\test\dfstest\Start Menu\programs").Copy appDataLocation & "\Microsoft\Windows\Start Menu\Programs"
Set objFileSys = Nothing

編輯:類型不匹配?

Dim objShell, strCmd, intRunError, strFolder, objFileSys
Dim Exceptions()
Dim Exception
Dim i

Set objShell = CreateObject( "WScript.Shell" )
appDataLocation=objShell.ExpandEnvironmentStrings("%APPDATA%")


Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(appDataLocation & "\Microsoft\Windows\Start Menu\Programs")

Exception(0) = appDataLocation & "\Microsoft\Windows\Start Menu\Programs\Access 2013"
Exception(1) = appDataLocation & "\Microsoft\Windows\Start Menu\Programs\Cameleon"  

For Each sf in MyFolder.SubFolders
    Exception = False
    For i = LBound(Exceptions) to UBound(Exceptions)
        If lCase(sf.Path) = lCase(Exceptions(i)) Then
            Exception = True
            Exit For
        End If
    Next
    If Not Exception Then
        deleteSubFolders
        sf.Delete
    End If
Next

Public Sub deleteSubFolders(byRef MyFolder, exclFolder)
    Dim sf
    For Each sf in MyFolder.SubFolders
        If not (lCase(sf.Path) = lCase(exclFolder)) Then
            deleteSubFolders sf, exclFolder
            sf.Delete
        End If
    Next
End Sub

' delete all files in root folder
for each f in folder.Files
   On Error Resume Next
   name = f.name
   f.Delete True
Next

Set objFileSys = CreateObject("Scripting.FileSystemObject")
objFileSys.GetFolder("\\test\dfstest\Start Menu\programs").Copy appDataLocation & "\Microsoft\Windows\Start Menu\Programs"
Set objFileSys = Nothing

答案1

對於多個條件,您可以使用例如陣列和循環來檢查所有條件:

Dim Exceptions(10) as String
Dim Exception as Boolean

Exception(0)= appDataLocation & "\Microsoft\Windows\Start Menu\Programs\Access 2013"
Exception(1)=...
...
Exception(9)=...

...

For Each sf in MyFolder.SubFolders
    Exception = False
    For i = LBound(Exceptions) to UBound(Exceptions)
        If lCase(sf.Path) = lCase(Exceptions(i)) Then
            Exception = True
            Exit For
        End If
    Next i
    If Not Exception Then
        deleteSubFolders sf, exclFolder
        sf.Delete
    End If
Next sf

(我對VBA更有經驗,也無法測試它,所以如果沒有小的修正,它可能無法工作,只是輸入它來解釋我的想法)

相關內容