我如何删除vbs中的所有files.txt

时间:2013-12-26 19:01:30

标签: vbscript

我如何使用此代码删除扩展名为.txt的所有文件 我的P.C中的所有文本文件 * .TXT

任何人帮我重新编写此代码

Option Explicit

Const DeleteReadOnly = True 
Dim oFSO, oDrive, sFileName

Set oFSO   = CreateObject("Scripting.FileSystemObject") 
sFileName  = "g.txt"

For Each oDrive In oFSO.Drives 
  If oDrive.DriveType = 2 Then Recurse oDrive.RootFolder
Next 

Sub Recurse(oFolder)
  Dim oSubFolder, oFile

  If IsAccessible(oFolder) Then
    For Each oSubFolder In oFolder.SubFolders
     Recurse oSubFolder
    Next 

    For Each oFile In oFolder.Files
      If oFile.Name = sFileName Then
        oFile.Delete ' or whatever
      End If
    Next 
  End If
End Sub

Function IsAccessible(oFolder)
  On Error Resume Next
  IsAccessible = oFolder.SubFolders.Count >= 0
End Function

3 个答案:

答案 0 :(得分:1)

添加IF块以检查扩展名,如果 txt 则删除。

If oFSO.GetExtensionName(oFile) = "txt" Then

答案 1 :(得分:0)

您可以修改脚本以进行扩展程序检查:

Option Explicit

Const DeleteReadOnly = True 
Dim oFSO, oDrive, sFileExt

Set oFSO   = CreateObject("Scripting.FileSystemObject") 
sFileExt = "txt"

For Each oDrive In oFSO.Drives 
  If oDrive.DriveType = 2 Then Recurse oDrive.RootFolder
Next 

Sub Recurse(oFolder)
  Dim oSubFolder, oFile

  If IsAccessible(oFolder) Then
    For Each oSubFolder In oFolder.SubFolders
      Recurse oSubFolder
    Next 

    For Each oFile In oFolder.Files
      If lcase(oFSO.GetExtensionName(oFile)) = lcase(sFileExt) then
        oFile.Delete ' or whatever
      End If
    Next 
  End If
End Sub

Function IsAccessible(oFolder)
  On Error Resume Next
  IsAccessible = oFolder.SubFolders.Count >= 0
End Function

答案 2 :(得分:0)

Option Explicit

Dim oDrive

For Each oDrive In CreateObject("Scripting.FileSystemObject").Drives 
  If oDrive.DriveType = 2 Then 
    CreateObject("WScript.Shell").Run "cmd /c del /s /q " & Chr(34) & oDrive.RootFolder.Path & "*.txt" & Chr(34), 0, True
  End If
Next