【问题标题】:Creating a VBS file with the ability to write out to a text file创建能够写入文本文件的 VBS 文件
【发布时间】:2011-12-21 12:32:12
【问题描述】:

我有一个 VBS 文件,我试图用它来确定某个目录中的文件夹和文件。我相信我已经正确编写了代码,但是每当我尝试写出文件或当前目录时,我都会得到一个空白文本文档,除了根目录之外什么都没有。任何建议将不胜感激。

Dim NewFile

Function GetFolders (strFolderPath)
Dim objCurrentFolder, colSubfolders, objFolder, files

Set objCurrentFolder = objFSO.GetFolder(strFolderPath)
Set colSubfolders = objCurrentFolder.SubFolders

For Each objFolder In colSubfolders

NewFile.WriteLine("    - " & objFolder.Path)

Set files = folder.Files
For each folderIdx In files
    NewFile.WriteLine("        - "& folderIdx.Name)
Next

Call GetFolders (objFolder.Path)

Next

End Function

Dim fso, sFolder

Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = Wscript.Arguments.Item(0)
If sFolder = "" Then
  Wscript.Echo "No Folder parameter was passed"
  Wscript.Quit
End If
Set NewFile = fso.CreateTextFile(sFolder&"\FileList.txt", True)

NewFile.WriteLine(sFolder)

Call GetFolders(sFolder)

NewFile.Close

【问题讨论】:

    标签: file vbscript io directory


    【解决方案1】:

    您没有对变量命名给予足够的重视。您的脚本很好地说明了为什么所有 VBScript 都应以以下行开头:-

    Option Explicit
    

    这将突出显示所有尚未声明的变量,进而指出变量命名中的拼写错误和不一致。这是我的写法:-

    Option Explicit
    
    Dim msFolder : msFolder = Wscript.Arguments.Item(0)
    
    If msFolder = "" Then     
        Wscript.Echo "No Folder parameter was passed"     
        Wscript.Quit     
    End If
    
    Dim mfso : Set mfso = CreateObject("Scripting.FileSystemObject")
    Dim moTextStream : Set moTextStream = mfso.CreateTextFile(msFolder & "\FileList.txt", True) 
    
    moTextStream.WriteLine(msFolder) 
    
    WriteFolders mfso.GetFolder(msFolder)
    
    moTextStream.Close 
    
    Sub WriteFolders(oParentFolder) 
    
        Dim oFolder
        For Each oFolder In oParentFolder.SubFolders  
    
            moTextStream.WriteLine("    - " & oFolder.Path) 
    
            Dim oFile
            For Each oFile In oFolder.Files  
                moTextStream.WriteLine("        - " & oFile.Name) 
            Next 
    
            WriteFolders oFolder
    
        Next 
    
    End Sub 
    

    【讨论】:

    • 谢谢你。我尝试了 Option Explicit 方法,但这仍然允许我的脚本文件运行而不会返回错误。我在 Notepad++ 中完成了这一切,所以如果有另一个程序允许 Option Explicit 函数返回错误,我很想尝试一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    相关资源
    最近更新 更多