immycee
immycee

Reputation: 21

How to read a text file to numbers and then get the total value of those numbers

I'm currently working on a script to find out how much free storage there is. The script checks a database to find out the store names then queries these using CMD. It then outputs a file with all the remaining storage. I cannot seem to find a way to combine all these values and bring back the total amount.

Script:

Dim objFileSys
Set objFileSys = CreateObject("Scripting.FileSystemObject")
If objFileSys.FileExists("a.txt") Then
    objFileSys.DeleteFile "a.txt"
    WScript.Echo ("old file found and deleted")    
Else
    WScript.Echo ("old file not found, script will continue")
End If

WScript.Sleep 500

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
Set oShell = WScript.CreateObject ("WScript.Shell")
Dim strRes
Dim strDc
Dim strSpc

objConnection.Open _
    "Provider=SQLOLEDB;Data Source=dls-bsp-sdb;" & _
    "Initial Catalog=DOM_SITE;" & _
    "User ID=*****;Password=*****"
objRecordSet.Open "****", objConnection

Do While Not objRecordSet.EOF 
   WScript.Sleep 1000
   strRes = objRecordset.Fields("Volume").Value
   strDc = ("cmd /c dir /-c " &strRes)+"| find /i ""bytes free"""
   WScript.Echo strRes
   oshell.Run "" & strDc + " >> a.txt"
   'WScript.Echo strSpc
   objRecordSet.MoveNext
Loop

objRecordSet.Close

WScript.Sleep 1000

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("a.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "               5 Dir(s)  ", "")
strNewText1 = Replace(strNewText, " bytes free", "")
strNewText2 = Replace(strNewText1, " ", "")

Set objFile = objFSO.OpenTextFile("a.txt", ForWriting)
objFile.WriteLine strNewText2 

objFile.Close

WScript.Sleep 1000

Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("a.txt",1)
Dim strLine

Do While Not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     wscript.echo strLine
Loop
WScript.Echo strLine
objFileToRead.Close

This outputs a text file containing something like

15363938635776
4314728202240
4250596589568
15386325426176
9204097486848
15406486990848

I know I can read the file using VBScript like

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("a.txt", ForReading)

Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    WScript.Echo strLine
Loop

objFile.Close

I just need the total instead of just viewing it as text.

Upvotes: 2

Views: 735

Answers (1)

Matt Cremeens
Matt Cremeens

Reputation: 5151

You can use an accumulator variable

mySum = 0

and then add to it as you loop

Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    mySum = mySum + CLng(strLine)
Loop

mySum now contains your total.

Upvotes: 2

Related Questions