Overwrite value in vbscript - vbscript

I have to update test.txt with new values i,e. delete value {"AAA":"777" , "BBB":"888"} and add {"ABC:"123","GHN:"246"} in tag
but my script append the value as {"AAA":"777" , "BBB":"888"} {"ABC:"123","GHN:"246"
strFile="test.txt"
Const ForAppending = 8
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile(strFile, ForAppending , True)
objFile.Write("{")
Dim dict
Set dict= CreateObject("Scripting.Dictionary")
dict.Add "ABC","123"
dict.Add "GHN","246"
k=dict.Keys
v=dict.Items
For j=0 to dict.Count-1
objFile.Write(chr(34)&k(j)&":"&chr(34)&v(j)&chr(34)&",")
Next
==============
Test.txt
[Valid]
api = https://test.com
Alpha = FALSE
tag = {"AAA":"777" , "BBB":"888"}

I've never used the dictionary object/don't know how, so this may not be a viable solution for you depending on whether you need certain things that the object provides... but without resorting to regex, could you not simply do something like this?
Dim fso, filecontent, file
Set fso = CreateObject("Scripting.FileSystemObject")
file = "C:\temp\test.txt"
filecontent = fso.OpenTextFile(file, 1, False).ReadAll
filecontent = Replace(filecontent, "{""AAA"":""777"" , ""BBB"":""888""}", "{""ABC:""123"",""GHN:""246""}")
fso.OpenTextFile(file, 2, True).Write filecontent

Related

VB Script - Find duplicate within same text file

I'm new to VBScript and I'm trying to:
Read a text file and find duplicates
Copy the duplicate line to another text file
I've already have the following code. I've Google-ed my question but most answers are comparison between two files. Any idea how to continue?
Dim Thistextfile, fso, obj, things
Const ForReading = 1
Thistextfile = "C:\Listofthings.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set obj = fso.OpenTextFile(Thistextfile,ForReading)
Do Until obj.AtEndOfStream
things = obj.ReadLine
things = Trim(things)
If Len(things) > 0 Then
WScript.Echo things
End If
Loop
obj.close
You could collect each line into a dictionary or .Net's ArrayList, then write each line to the new file if it already exists in that collection:
Dim Thistextfile, fso, obj, things
Const ForReading = 1
Thistextfile = "C:\Listofthings.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set obj = fso.OpenTextFile(Thistextfile,ForReading)
dim dictionary: set dictionary = CreateObject("Scripting.Dictionary")
dictionary.CompareMode = 1 'vbTextCompare
dim outputfile: set outputfile = fso.CreateTextFile("c:\duplicates.txt", true, true)
Do Until obj.AtEndOfStream
things = obj.ReadLine()
things = Trim(things)
If Len(things) > 0 Then
WScript.Echo things
End If
'if it already exists, it's a duplicate
if dictionary.exists(things) then
outputfile.writeline things
else
dictionary.add things, null
end if
Loop
outputfile.close
obj.close

Emailing preceded by text files consolidation into excel

I have two text files with following content:
file1.txt:
Windows 1.36
Linux 2.78
MacOS 3.45
Ubuntu 4.12
FreePhysicalMemory 30.12
TotalVisibleMemorySize 48.00
file2.txt:
MacOS 6.39
Windows 4.42
Linux 5.76
Android 3.46
FreePhysicalMemory 31.65
TotalVisibleMemorySize 48.00
output.xls:
OPERATING SYSTEM SERVER1 SERVER2
Windows 1.36 4.42
Linux 2.78 5.76
MacOS 3.45 6.39
Ubuntu 4.12 0.00
Android 0.00 3.46
FreePhysicalMemory 30.12 31.65
TotalVisibleMemorySize 48.00 48.00
I want to achieve following two things in a VBScript program or in any, which is appropriate to run on windows server:
Insert the contents of both file1.txt and fil2.txt in a excel
sheet output.xls like above.
Mail the content of output.xls file as a body in email.
I think, Point2 is being achieved using below code but not getting how can i achieve Point1 in same program.
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const FileToBeUsed = "c:\output.xls"
Dim objCDO1
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(FileToBeUsed, ForReading)
Set objCDO1 = CreateObject("CDO.Message")
objCDO1.Textbody = f.ReadAll
f.Close
objCDO1.TO ="sunny#abc.com"
objCDO1.From = "dontreply#abc.com"
objCDO1.Subject = "Server Memory"
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration /sendusing") = 2
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtpb.intra.abc.com"
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration /smtpserverport") = 25
objCDO1.Configuration.Fields.Update
objCDO1.Send
Set f = Nothing
Set fso = Nothing
Any suggestion is highly appreciated.
Note:My purpose here is to send email with properly formatted and aligned data.
EDIT1:
This is all i could do regarding points 1,2,3.
Don't know how to consolidate all this in a HTML email Body format..:(
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso,f,objFSO,objFile,objRE, FileName
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
const strFileName1 = "D:\file1.txt"
const strFileName2 = "D:\file2.txt"
Set objFile = objFSO.OpenTextFile(strFileName1, fsoForReading) + objFSO.OpenTextFile(strFileName2, fsoForReading)
objobjFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Set objRE = New RegExp
With objRE
.Pattern = "[A-Z][0-9]"
.IgnoreCase = False
.Global = False
End With
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
const strFileName1 = "D:\file1.txt"
const strFileName2 = "D:\file2.txt"
Set objFile = objFSO.OpenTextFile(strFileName1, fsoForReading) + objFSO.OpenTextFile(strFileName2, fsoForReading)
Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
Set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
For Each strMatch in colMatches
Wscript.Echo strSearchString
Next
End If
Loop
objFile.Close
Class memory1class
Public operatingsystem, memory
End Class
Dim memory1dict: Set memory1 = CreateObject("Scripting.Dictionary")
Dim memory2dict: Set memory2 = CreateObject("Scripting.Dictionary")
Dim memory1: Set memory1 = new memory1class
With memory1
.operatingsystem = "?"
.memory = "?"
End With
memory1dict.Add "1", memory1
Dim memory1details: Set memory1details = memory1dict.Item("1")
WScript.StdOut.WriteLine("operatingsystem:" & memory1details.first & " " & memory1details.memory & " )
I don't want to directly give you code, because this is a good opportunity for you to learn more about the different options you have available for solving the problem yourself, but I can give you a rough outline of what I would do.
Open the two text files for reading. Windows provides a "Scripting" library which contains the FileSystemObject. You would declare an instance of it as below, and you can google for the specifics of how to use it to open a text file:
Set fso = CreateObject("Scripting.FileSystemObject")
Read each file in a line at a time. Parse each line to get the "name" part and the "number" part as distinct values. You can do this by combining the InStr, InStrRev, and Mid functions or you can use the more powerful RegExp library (VBScript's Regular Expression class).
Set re = New RegExp
Store each "name" and "value" into a data structure for later use - I recomment an associative array such as VBScript's Dictionary class. Using a separate one for each text file will allow you to cross-reference them later.
Set dictStats1 = CreateObject("Scripting.Dictionary")
To display the data formatted correctly in the email, I suggest using an HTML table. In addition to the TextBody, the CDO.Message object has an HTMLBody property to allow you to give the email structured formatting instead of just raw text. Extrapolating from the simple example on w3school.com, you can construct a function that will accept the two dictionaries and use them to construct the HTML table and return it as a string to be loaded into the email via the HTMLBody property.
I hope that helps! Let me know if you have any questions about the specifics.

Extract text string from file

I am writing a utility to collect all system information from all devices on a network to an XML document, and one of the values is a certain software version number. Unfortunately the version number is only stored in a single text file on each machine (c:\master.txt) the even more fun part is, each text file is formatted differently depending on the image that was used.
One could say
Product Number: 11dsSt2 BRANDONII,STNS6.0.2.200
The next
Ver: 22335TS BOX2 S6.1.3.011,STN
and so on.
What I did, is create a VBS that looks for a number pattern that matches the version pattern, which is
[A-Z]#.#.#.###
This works, however I just want to output that pattern, not the entire line. Here is my code. Any Suggestions?
Const ForReading = 1
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "[A-Z]{1}[0-9]{1}.[0-9]{1}.[0-9]{1}.[0-9]{3}"
objregex.global = true
objregex.ignorecase = true
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\master.txt", ForReading)
Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
Addmatch
End If
Loop
objFile.Close
Sub Addmatch 'Creates a text file with the part number
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile1 = objFSO.OpenTextFile("C:\test.txt", ForAppending, True)
objFile1.Writeline strSearchString
objFile1.Close
end sub
You're storing the entire line you read from the file (that you have in strSearchString) instead of just the matched text. Use something like this instead (untested!):
if ColMatches.Count > 0 then
AddMatch(ColMatches(0)) ' Just grab the matched text and pass to AddMatch
End If
Sub AddMatch(strMatchedText) ' Change to accept parameter of text to write out
' Other code
objFile1.Writeline strMatchedText
objFile1.Close
End Sub
Use the first/one and only match to obtain the value, and pass this to a slightly modified version of Addmatch:
If colMatches.Count > 0 Then
Addmatch colMatches(0).Value
End If
...
Sub Addmatch(sWhatToWriteLn) ' some truthful comment
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFSO.OpenTextFile("C:\test.txt", ForAppending, True)
objFile1.Writeline sWhatToWriteLn
...

Reading data from a file with a variable name - VBScript

I'm trying to count the number of lines in a text file using VBScript. I have managed to do this without a problem for a text file with a fixed name. EG: "C:\Orig\sample.txt"
However, our filenames change daily, EG: "C:\Orig\sample*todaysdate*.txt"
I have looked high and low for a way to 'read' a file with a variable name and have had no luck.
What I have so far for a fixed file name is:
Dim oFso, oReg, sData, lCount, linesum
Const ForReading = 1, sPath = "C:\Orig\sample.txt"
Set oReg = New RegExp
Set oFso = CreateObject("Scripting.FileSystemObject")
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set oFso = Nothing
Set oReg = Nothing
This works perfectly well, but I just cannot find the correct syntax for a variable file name.
If it is of any help, the file I'm looking to interrogate will be the ONLY file in the containing folder.
Is anybody able to offer any assistance? Many thanks.
I have now tried the following:
Dim objFso, objReg, sData, lCount
Const ForReading = 1
sPath = "C:\Orig"
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(sPath)
For Each objFile in objFolder.Files
Set objReg = New RegExp
sData = objFso.OpenTextFile(sPath, ForReading).ReadAll
With objReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set objFso = Nothing
Set objReg = Nothing
Set objFolder = Nothing
set sData = Nothing
Next
But on line 9 I am getting a 'Permission denied' error. I have checked folder permissions and file permissions and I have full rights.
Does anybody have any ideas?
Thanks in advance.
Loop through the files in the folder instead. There's no need to name the file directly.
Dim oFso, oReg, sData, lCount, linesum
Const ForReading = 1
sPath = "C:\Orig\sample\"
Set oFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(sPath)
For Each objFile in objFolder.Files
Set oReg = New RegExp
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set oFso = Nothing
Set oReg = Nothing
Next

How to read from a text file using VBScript?

I am looking to see a simple way to read from and write to a text file using VBScript.
I think this is an acceptable method for writing to a file.
Dim f,
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile("C:\test.txt", True, True)
f.WriteLine("Data to Add to file.")
f.Close
However, I would like to know how to read from a file in a similar fashion.
Use first the method OpenTextFile, and then...
either read the file at once with the method ReadAll:
Const ForReading = 1
Dim file, content
Set file = fso.OpenTextFile("C:\test.txt", ForReading)
content = file.ReadAll
or line by line with the method ReadLine:
Const ForReading = 1
Dim dict, file, row, line
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", ForReading)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close

Resources