vb script if statement - if-statement

I want to edit a file with VB if the word that must to be in file isn't exist.
when execute this file, I want if condition was true do nothing but all file content was erase.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
End If
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close

that becouse strNewText will be null when your condition true. and still replace the strText with your empty strNewText.
Keep your works in side the if(). so it will solve the Problem.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForReading)
strText = objFile.ReadAll
objFile.Close
strSearchFor = "this word must to exist"
If InStr(1, strText, strSearchFor) > 0 then
'do nothing
else
strNewText = Replace(strText,"this word must to delete","this word must to exist" )
Set objFile = objFSO.OpenTextFile("C:\path\to\file.html", ForWriting)
objFile.WriteLine strNewText
objFile.Close
End If

Related

VBS How to replace any color string (#******) with new value

trying to replace in a folder different color values with a new one this is my starting code:
Option Explicit
Dim objFSO, strFolder, objFolder, objFile
Dim strOldValue, strNewValue, objRead, strContents, objWrite
Const ForReading = 1
Const ForWriting = 2
strFolder = "..\..\chrome\OPCEN\TABS"
strOldValue = "#******"
strNewValue = "#F5F5F5"
UPDATE: this is the working code using RegEx (but is pointing to the file not to the whole folder)
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("..\..\chrome\OPCEN\TABS\tabs.css", ForReading)
strText = objFile.ReadAll
objFile.Close
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = False
objRegEx.Pattern = "\#[A-Z 0-9]{6}"
strNewText = objRegEx.Replace(strText, "#F5F5F5")
Set objFile = objFSO.OpenTextFile("..\..\chrome\OPCEN\TABS\tabs.css", ForWriting)
objFile.WriteLine strNewText
objFile.Close
Use For Each loop to processing files and Regular Expressions to replace your strings.
Try my way :
Const ForReading = 1
Const ForWriting = 2
Set fso=Createobject("Scripting.FileSystemObject")
Set objRegEx = New RegExp
FolderName = "..\..\chrome\OPCEN\TABS"
Set objFolder = fso.GetFolder(FolderName)
Set objFileCol = objFolder.Files
For Each obFile In objFileCol
If Right(obFile,3)="css" Then 'Check all files extensions.
Set objFile = fso.OpenTextFile(obFile, ForReading)
strText = objFile.ReadAll
objFile.Close
objRegEx.Global = True
objRegEx.IgnoreCase = False
objRegEx.Pattern = "\#[A-Z 0-9]{6}"
strNewText = objRegEx.Replace(strText, "#F5F5F5")
Set WriteFile = fso.OpenTextFile(obFile, ForWriting)
WriteFile.WriteLine strNewText
WriteFile.Close
End if
Next

Extract all lines of a file between 2 delimiters without them in VBScript Regex

I try to Extract all lines of a file between 2 strings in another file and without these delimiters.
Example:
[General]
Description=Description
[extractSection]
First Line extracted. It is not an ini section
Last Line extracted
[OthersSection]
blablabla
It seems to work with this script. One of my first vbs.
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
If objFS.FileExists(strTemp) Then objFS.DeleteFile(strTemp)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If isReading = True Then
If instr(strline,"[") Then
Set objOutFile = objFS.CreateTextFile(strTemp, True)
objOutFile.Write(strLine1)
objOutFile.Close
Exit Do
Else
strline1 = strline1 & strline & vbNewLine
End If
Else
If instr(LCase(strline),"[extractsection]") Then
isReading = True
End If
End If
Loop
objFile.Close
But it seems not very optimized, I have files up to 8Mb.
I would like to try the same thing using Regex. I never used, I have to learn.
I have this as beginning: \[extractsection\]([\s\S]*?)\[[\s\S]
But I would like without the delimiters.
Thank you Wiktor. It seems it is OK with (?<=\[extractSection\]\n)(.*(?:\n(?!\[).*)*) Just let me know what is best (Ram | speed) vs my ReadLine script on top, please
You can give a try for this vbscript without a Regex :
Option Explicit
Dim strFile,strTemp,Full_String,First_Delimiter,Second_Delimiter,Extracted_Data
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
Full_String = ReadFileText(strFile)
First_Delimiter = "[extractSection]"
Second_Delimiter = "[OthersSection]"
Extracted_Data = String_Between(Full_String,First_Delimiter,Second_Delimiter)
wscript.echo Extracted_Data
Write2File Extracted_Data,strTemp
'************************************************************************************************
Function String_Between(ByVal Full_String, ByVal First_Delimiter, ByVal Second_Delimiter)
Dim Pos,Pos2
Pos = InStr(Full_String, First_Delimiter)
Pos2 = InStr(Full_String, Second_Delimiter)
If Pos = 0 Or Pos2 = 0 Then
String_Between = "Missing Delimiter"
Exit Function
End If
String_Between = Mid(Full_String, Pos + Len(First_Delimiter), Pos2 - (Pos + Len(First_Delimiter)))
End Function
'***********************************************************************************************
Function ReadFileText(sFile)
Dim objFSO,oTS,sText
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(sFile) Then
MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) &_
" dosen't exists !",VbCritical,"CRITICAL ERROR"
Wscript.Quit
Else
Set oTS = objFSO.OpenTextFile(sFile)
sText = oTS.ReadAll
oTS.close
set oTS = nothing
Set objFSO = nothing
ReadFileText = sText
End if
End Function
'*********************************************************************************************
Sub Write2File(strText,OutputFile)
Dim fs,ts
Const ForWriting = 2
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(OutputFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
And this one with RegEx
Option Explicit
Dim strFile,strTemp,Full_String,First_Delimiter,Second_Delimiter,Extracted_Data
strFile = "E:\Temp\Test.txt"
strTemp = "E:\Temp\Temp.txt"
Full_String = ReadFileText(strFile)
First_Delimiter = "[extractSection]"
Second_Delimiter = "[OthersSection]"
Extracted_Data = ExtractData(Full_String,First_Delimiter,Second_Delimiter)
wscript.echo Extracted_Data
Write2File Extracted_Data,strTemp
'***********************************************************************************************
Function ExtractData(Full_String,Start_Delim,End_Delim)
Dim fso,f,r,Matches,Contents,Data
Start_Delim = Replace(Start_Delim,"[","\[")
Start_Delim = Replace(Start_Delim,"]","\]")
End_Delim = Replace(End_Delim,"[","\[")
End_Delim = Replace(End_Delim,"]","\]")
Set r=new regexp
r.pattern = "(?:^|(?:\r\n))(:?"& Start_Delim &"\r\n)([\s\S]*?)(?:\r\n)(?:"& End_Delim &")"
Set Matches = r.Execute(Full_String)
If Matches.Count > 0 Then Data = Matches(0).SubMatches(1)
ExtractData = Data
End Function
'***********************************************************************************************
Function ReadFileText(sFile)
Dim objFSO,oTS,sText
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(sFile) Then
MsgBox "CRITICAL ERROR " & VbCrLF & "The File "& DblQuote(sFile) &_
" dosen't exists !",VbCritical,"CRITICAL ERROR"
Wscript.Quit
Else
Set oTS = objFSO.OpenTextFile(sFile)
sText = oTS.ReadAll
oTS.close
set oTS = nothing
Set objFSO = nothing
ReadFileText = sText
End if
End Function
'*********************************************************************************************
Sub Write2File(strText,OutputFile)
Dim fs,ts
Const ForWriting = 2
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(OutputFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

Extract text from last line in log file using vbscript

I have a log file formatted as such:
AssetTag USERNAME Date Time Local
abc123456 Sam 10/15/2015 8:22:14am Local
abc87363 Joe 10/15/2015 8:55:59am Local
I need to extract the USERNAME from the last line of the log file using a batch file. IE: Extract 'Joe' from the last line.
I am thinking some sort regex to find the first space and select the text between the first space and the next space...that should be 'Joe'...
I am using this to extract the last line:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\logs\UserAudit.log", ForReading)
Do Until objFile.AtEndOfStream
strNextLine = objFile.ReadLine
If Len(strNextLine) > 0 Then
strLine = strNextLine
End If
Loop
objFile.Close
Wscript.Echo strLine
EDIT: it is actually 2 tabs that separate the assettag and the username and 1 tab that separate the username and the date
I figured it out with a little more google...
What the below script does..
1) Prompt for asset tag
2) reads last line from log file, extracts username
3)looks up username in AD to find the Staff Name
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
strAsset= INPUTBOX("Please enter the Asset Tag:")
strLog = "\\" & strAsset & "\C$\Logs\UserAudit.log"
'Set objFile = objFSO.OpenTextFile("C:\logs\UserAudit.log", ForReading)
Set objFile = objFSO.OpenTextFile(strLog, ForReading)
Do Until objFile.AtEndOfStream
strNextLine = objFile.ReadLine
If Len(strNextLine) > 0 Then
strLine = strNextLine
End If
Loop
objFile.Close
intStart = InStr(strLine, " ")
If intStart <> 0 Then
intStart = intStart + 2
strText = Mid(strLine, intStart, 250)
For i = 1 to Len(strText)
If Mid(strText, i, 1) = " " Then
Exit For
Else
strData = strData & Mid(strText, i, 1)
End If
Next
End If
'Username from Log file
Wscript.Echo strData
'Lookup Account for Staff Name
SET objSystemInfo = CREATEOBJECT("ADSystemInfo")
strDomain = objSystemInfo.DomainShortName
strUser = strData
wscript.echo GetUserDN(strUser,strDomain)
strAD = GetUserDN(strUser,strDomain)
intStart = InStr(strAD, "CN=")
If intStart <> 0 Then
intStart = intStart + 3
strText = Mid(strAD, intStart, 250)
For i = 1 to Len(strText)
If Mid(strText, i, 3) = ",OU" Then
Exit For
Else
strName = strName & Mid(strText, i, 1)
End If
Next
End If
wScript.echo strName
FUNCTION GetUserDN(BYVAL strUserName,BYVAL strDomain)
SET objTrans = CREATEOBJECT("NameTranslate")
objTrans.Init 1, strDomain
objTrans.SET 3, strDomain & "\" & strUserName
strUserDN = objTrans.GET(1)
GetUserDN = strUserDN
END FUNCTION
'Cleanup
intStart=""
strUser=""
strDomain=""
strName=""
strAD=""
strText=""
strLine=""
strNextLine=""

Find and Replace string in a .txt file with VBscript

I am trying to figure out how to use vbscript to:
1 - open a .csv file as a .txt file
2 - search for a certain string of text that is located randomly throughout the text
3 - replace that string with a different string.
I have found an article that helped me learn how to replace an entire line in a .txt document, but so far have had no luck finding anything about replacing just certain characters within the line.
Thanks!
Here is the code I am using currently:
Const ForReading = 1
Const ForWriting = 2
'Setting up our objects and focusing on the text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If strLine = "Myer" Then
strLine = "Mike"
End If
strContents = strContents & strLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForWriting)
objFile.Write(strContents)
objFile.Close
The text file it references says:
Ken Myer
Fabrikam
Pilar Ackerman
Wingtip Toys
Jeff Hay
Fabrikam
Ellen Adams
Northwind Traders
Myer
(End of text file). So essentially, I have gotten the code to successfully change the "Myer" that is on its own line to "Mike". What I am having a hard time with is changing the "Myer" in the first line to "Mike". Hopefully this helps clarify things a bit...I'm extremely new at this so not sure of the language I should be using to describe the problem.
Use Replace on the file's content obtained by .ReadAll() and .Write the result back. In code:
Option Explicit
Dim goFS : Set goFS = Createobject("Scripting.FileSystemObject")
Dim goWAU : Set goWAU = WScript.Arguments.Unnamed
WScript.Quit main()
Function main()
main = 1 ' assume error
If 3 = goWAU.Count Then
If goFS.FileExists(goWAU(0)) Then
Dim s : s = goFS.OpenTextFile(goWAU(0)).ReadAll()
If 0 < Instr(s, goWAU(1)) Then
goFS.CreateTextFile(goWAU(0)).Write Replace(s, goWAU(1), goWAU(2))
WScript.Echo "done"
main = 0
Else
WScript.Echo goWAU(1), "not found"
End If
Else
WScript.Echo goWAU(0), "does not exist"
End If
Else
WScript.Echo "need 3 args: fspec, find, replacement"
End If
End Function
output:
copy con 28350055.csv
1,2,3
4,5,6
^Z
cscript 28350055.vbs 28350055.csv 5 4711
done
type 28350055.csv
1,2,3
4,4711,6
cscript 28350055.vbs 28350055.csv 5 4711
5 not found
cscript 28350055.vbs 28350055.cs 5 4711
28350055.cs does not exist
Use that demo to determine what is needed to solve your real world problem.
I'm extremly new too, so i didnt get what the other answer do in the code, but i figured out in the last answer about "Replace" and use in your code for do what you need, and the result is this:
Const ForReading = 1
Const ForWriting = 2
'Setting up our objects and focusing on the text file.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\Documents\Script Practice\TextFiles-2-4-15-Folder\ReadandWrite\Textlook.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
strLine = Replace(strLine,"Myer","Mike")
' If strLine = "Myer" Then
' strLine = "Mike"
' End If
strContents = strContents & strLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("F:\BIBLIOTECAS\Archivos\TEST.txt", ForWriting)
objFile.Write(strContents)
objFile.Close

VBS RegEx Search and Replace

I am attempting to use a vbs script to replace the limit value in a .ini file that contains the following line:
CC_refund_limit=####.##
Unfortunately the ####.## can be any dollar value. I am replacing with a standard:
CC_refund_limit=500.00
I have attempted the following with every variation of \d \d+ enclosed in every bracket known to mankind and have even attempted [0-999] on a test file. The only way I can get this to work has been with the following code and only if the string contains an actual dollar value as written. I have over 1600 instances on as many different servers to replace this on.
Any guidance would be appreciated:
`Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "CC_refund_limit=200.00", "CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close
`
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForReading)
strText = objFile.ReadAll
objFile.Close
Set r = New Regexp
With r
.pattern = "CC_refund_limit=\d+\.\d+"
.global = true
End with
StrNewText = r.Replace(strText,"CC_refund_limit=500.00")
Set objFile = objFSO.OpenTextFile("C:\EDC\Edc.ini", ForWriting)
objFile.WriteLine strNewText
objFile.Close