用vbscript实现在文本文件中搜索两个项

2019-01-16 08:36:18于丽

此时,我们可进行第一次搜索了。 下面这行代码使用 InStr 函数来确定是否可在变量 strContents 中的某个位置找到字符串 Windows 2000:
If InStr(strContents, "Windows 2000") Then
如果 InStr 为 True,则我们将 blnFound 的值设置为 True;如果 InStr 为 False,我们将直接跳至下一个搜索。 在下一个搜索中,我们重复此过程,这次将搜索字符串 Windows XP:
If InStr(strContents, "Windows XP") Then
如果找到了 Windows 2000 或 Windows XP(或二者均找到了),则 blnFound 将为 True;如果两者均未找到,则 blnFound 将仍为 False。 在脚本的末尾,我们检查 blnFound 的值,并指出是否在文件中找到了一个或多个搜索短语。
但如果您想知道文件中是否同时包含这两个搜索短语,该怎么办呢? 我们将不再对此做详细阐述,但下面的脚本可告诉您是否可在文件中同时找到两个目标短语:
Const ForReading = 1
intFound = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:ScriptsTest.txt", ForReading)
strContents = objFile.ReadAll
objFile.Close
If InStr(strContents, "Windows 2000") Then
    intFound = intFound + 1
End If
If InStr(strContents, "Windows XP") Then
    intFound = intFound + 1
End If
If intFound = 2 Then
    Wscript.Echo "The text file contains both Windows 2000 and Windows XP."
Else
    Wscript.Echo "The text file does not contain both Windows 2000 and Windows XP."
End If
是的,该脚本的确与前面的脚本很相似。 最大的不同之处在于我们没有使用 True-False 变量;而是使用了一个名为 intFound 的计数器变量。 该脚本首先搜索 Windows 2000;如果找到了该短语,则会将 intFound 加 1。(由于 intFound 开始时为 0,这就意味着此时 intFound 将等于 1。) 
然后该脚本将搜索 Windows XP,如果找到了该短语,会将 intFound 的值加 1。最终结果如何呢? 在脚本末尾,只有同时找到了两个目标短语,intFound 才会等于 2;如果 intFound 等于 0 或 1,则表示一个都没找到或只找到了一个目标短语。 此时所要做的就是回显搜索结果。