如何将文本文件读取到数字,然后获取这些数字的总值

时间:2016-07-12 12:51:28

标签: vbscript

我目前正在制作一个脚本,以了解有多少免费存储空间。 该脚本检查数据库以找出商店名称,然后使用CMD查询这些名称。 然后它输出一个包含所有剩余存储空间的文件。 我似乎无法找到一种方法来组合所有这些值并带回总量。

脚本:

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

这会输出包含

之类的文本文件
15363938635776
4314728202240
4250596589568
15386325426176
9204097486848
15406486990848

我知道我可以使用像

这样的VBScript读取文件
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

我只需要总数而不只是将其视为文本。

1 个答案:

答案 0 :(得分:2)

您可以使用累加器变量

mySum = 0

然后在循环时添加到

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

mySum现在包含您的总数。