Search code examples
windowscmdvbscriptfinderrorlevel

Calling windows command prompt and use find to check if a string is in a text file


I want to use:

Set cmdLine = CreateObject("WScript.Shell")

Then I want to do something like:

check = cmdLine.Exec("%comspec% /C find /N "End of Report" D:\test3.txt)

But I am not very familiar with coding in the command prompt... so I don't really know what I am doing. But I want to search for a string of text in a .txt file and see if it exist or not... I don't really need a to know what line number it is found on or anything... just if it was found or not.

PS- I am going about it this way to avoid having to open the text file if the string isn't found.

I read that find has one of three %errorlevel% responses.

0 – The string you were searching for was found. 1 – The string you were searching for was not found. 2 – This means you had a bad switch or your parameters were incorrect.

I don't really know what they mean by %errorlevel% responses... but I am hoping to do something like"

if check = 0 then
    'do something
End if

meaning... If the string I am searching for is found... then do something...


Solution

  • Here was the solution i found that worked for my purposes.

    Dim cmdLine As Object
    Dim result As String
    Dim SearchStr As String
    Dim FilePath As String  
    
    Set cmdLine = CreateObject("WScript.Shell")
    result = cmdLine.Exec("%comspec% /C Find " & SearchStr & " " & Chr(34) & FilePath & Chr(34)).STDOut.ReadAll