动态和递归搜索Windows文件夹中的字符串&子文件夹

时间:2016-02-22 11:42:15

标签: windows batch-file recursion vbscript

我正在尝试使用以下用例实现递归搜索脚本: -

  1. 用户可以输入要搜索的字符串和目录。
  2. 脚本将列出所有带有与第1点匹配的路径的文件(可能在单独的文件中)。
  3. 我尝试使用批处理脚本并尝试从html页面运行以传递参数(字符串和目录)。失败as mentioned over stackoverflow(由于javascripts无法访问文件系统。)

    我的批处理脚本是: - findstr /s /i /n /C:@name= *.* v > results.txt

    现在我想知道我的要求是否可以用批处理文件来完成,或者我需要切换到vbscript。请建议。 我对vbscript一无所知。

    我无法在Windows工作站上安装任何第三方工具。

1 个答案:

答案 0 :(得分:2)

这是vbscript,如果从本地页面运行,则不会触发安全对话框。

On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")

Dirname = InputBox("Enter Dir name")
Searchterm = Inputbox("Enter search term")

ProcessFolder DirName

Sub ProcessFolder(FolderPath)

    Set fldr = fso.GetFolder(FolderPath)

    Set Fls = fldr.files
    For Each thing in Fls
        Set contents = thing.OpenAsTextStream 
        If Instr(contents.readall, searchterm) then wscript.echo thing.path
    Next

    Set fldrs = fldr.subfolders
    For Each thing in fldrs
'        wscript.echo thing.name
        ProcessFolder thing.path
    Next

End Sub

编辑 EDIT2(添加浏览文件夹)

在一个HTA中(我必须从头开始 - 我无法让你的脚本工作)。

<HTML> 
<HEAD><TITLE>Simple Validation</TITLE> 
<SCRIPT LANGUAGE="VBScript">
Dim Dirname
Dim Searchterm
Dim FSO
Dim objOutFile

Sub Browse
    On Error Resume Next
    Set bffShell = CreateObject("Shell.Application")
    Set bff = bffShell.BrowseForFolder(0, "Select the My Documents folder", 9)
    If Err.number<>0 Then
        MsgBox "Error Setting up Browse for Folder"

    Else
        A = bff.ParentFolder.ParseName(bff.Title).Path
        If err.number=424 then err.clear
            tb2.value = A
    End If
End Sub

Sub Search
    On Error Resume Next
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objOutFile = fso.CreateTextFile("results.txt",True)
    Dirname = tb2.value
    Searchterm = tb1.value
    ProcessFolder DirName
End Sub

Sub ProcessFolder(FolderPath)
    On Error Resume Next
    Set fldr = fso.GetFolder(FolderPath)

    Set Fls = fldr.files
    For Each thing in Fls
        Set contents = thing.OpenAsTextStream
        If err.number = 0 then
            Test = Instr(contents.readall, searchterm) 
            If Isnull(test) = false then If Test > 0 then ObjOutFile.WriteLine thing.path
        Else
            err.clear
        End If
    Next

    Set fldrs = fldr.subfolders
    For Each thing in fldrs
        ProcessFolder thing.path
    Next

End Sub


</script>
</head>
<body>
<p><INPUT Name=tb1 TYPE=Text Value="Search">
<p><INPUT Name=tb2 TYPE=Text Value="Folder"> <INPUT NAME="Browse" TYPE="BUTTON" VALUE="Browse" OnClick=Browse>
<p><INPUT NAME="Search" TYPE="BUTTON" VALUE="Search" OnClick=Search>
</body>
</html>