/build/static/layout/Breadcrumb_cap_w.png

vbs script to search a string in a textfile and add string if not found

Hi

I'm searching a vbs script which searches a string in a defined textfile.
If the string is not found it should be added in the file.
Can somebody help me?

Thank you.

2 Comments   [ + ] Show comments
  • How can I replace the string in the same line if is found in the text file.

    Please help me i wand to do this as soon as possible.

    Thanks in advance. - ChinnuM 9 years ago
  • what about if i need the script to read a file and search a text and change it with another text. - Sanfoor 9 years ago

Answers (7)

Answer Summary:
Posted by: pjgeutjens 14 years ago
Red Belt
1
This should work:


Set objFSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set objShell = Wscript.CreateObject("Wscript.Shell")
Const FORREADING = 1
Const FORWRITING = 2
Const FORAPPENDING = 8
Dim sToSearch: sToSearch = "What you're Looking for"
Dim sFileName: sFileName = "C:\Temp.txt"
Dim sContent, Found
If Not objFSO.FileExists(sFileName) Then
MsgBox "File Not Found"
WScript.Quit 0
End If
Set TxtFile = objFSO.OpenTextFile(sFileName,FORREADING)
sContent = TxtFile.ReadAll
If InStr(sContent,sToSearch) Then Found = True End If
Set TxtFile = Nothing
If Not Found Then
Set TxtFile = objFSO.OpenTextFile(sFileName,FORAPPENDING)
TxtFile.WriteLine sToSearch
End If
Posted by: AcIvI 14 years ago
Senior Yellow Belt
0
Thank you.
That works just as I need it.
Posted by: pjgeutjens 14 years ago
Red Belt
0
You don't actually need to define the Shell object even. Just a "bad" habit of mine when coding VBS. Also at the end you might want to add another

Set TxtFile = Nothing
Posted by: TimoP 9 years ago
Orange Belt
0
You might want to close the file after you have done reading/writing/appending to it and before setting it to nothing.
TxtFile.Close in this case.
Posted by: EdT 9 years ago
Red Belt
0
You might also want to make the code case-insensitive if there is ANY doubt that the case may vary in the string you are searching for..
Posted by: AcIvI 9 years ago
Senior Yellow Belt
0
This question of me is about 5.5 years old.
Still thank you for your answers.
Posted by: Sanfoor 9 years ago
Senior Yellow Belt
0
it's a very helpfull script
but what about if i need the script to read a file and search a text and change it with another text.
Rating comments in this legacy AppDeploy message board thread won't reorder them,
so that the conversation will remain readable.
 
This website uses cookies. By continuing to use this site and/or clicking the "Accept" button you are providing consent Quest Software and its affiliates do NOT sell the Personal Data you provide to us either when you register on our websites or when you do business with us. For more information about our Privacy Policy and our data protection efforts, please visit GDPR-HQ