Tuesday, July 17, 2012

VBScript to Find and Replace

I have been using this script for some time now. I took inputs from some sites to create this VBScript. I have modified it to my needs. I want to share this and keep it gfor my reference for future use as well.
I am searching for a text and replacing it with the User input of mail id.

'-----------------------------------------------------
'Use the below function if you want it to run from commandline and take input from users.
'If WScript.Arguments.Count <> 2 then
'  WScript.Echo "usage: Find_And_replace.vbs filename word_to_find replace_with "
'  WScript.Quit
'end If
MailID=InputBox("Please enter your E-Mail ID")
sFind="abcxyz.com"
Set oshell=CreateObject("Wscript.shell")
prog=oshell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
TargetFile= prog & "\App\config.ini"
TempFile= prog & "\App\config1.ini"
FindAndReplace TargetFile, sFind, MailID
WScript.Echo "Operation Complete"

function FindAndReplace(strFile, strFind, strReplace)
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objInputFile = objFSO.OpenTextFile(strFile,1)
    'strTempDir = objFSO.GetSpecialFolder(2)
    Set objTempFile = objFSO.OpenTextFile(TempFile,2,true)
    do until objInputFile.AtEndOfStream
        objTempFile.WriteLine(Replace(objInputFile.ReadLine, strFind, strReplace))
    loop
    objInputFile.Close
    Set objInputFile = Nothing
    objTempFile.Close
    Set objTempFile = Nothing
    objFSO.DeleteFile strFile, true
    objFSO.MoveFile TempFile, strFile
    Set objFSO = Nothing
end function 
'-----------------------------------------------------

You can modify this script based on your needs and use it.

No comments: