Jump to content
Strawberry Orange Banana Lime Leaf Slate Sky Blueberry Grape Watermelon Chocolate Marble
Strawberry Orange Banana Lime Leaf Slate Sky Blueberry Grape Watermelon Chocolate Marble

MSFN is made available via donations, subscriptions and advertising revenue. The use of ad-blocking software hurts the site. Please disable ad-blocking software or set an exception for MSFN. Alternatively, register and become a site sponsor/subscriber and ads will be disabled automatically. 


Sign in to follow this  
Pygowsky

Parsing with VB Script

Recommended Posts


This will not do all you want, what it does is remove the line with numbers also

1. Echoes the version number of Windows Script Host installed on the computer.

this will also remove the blank lines from the file. It Produces a Test_ScriptingSamples2.txt

with the contents added. The script uses vbs regex to search for the line numbers, I don't

use vbs regex very much so don't know how to use it to full capacity.

VBS Regex

Save As Demo_Regex.vbs


'-> Object For Run Time
Dim Act :Set Act = CreateObject("WScript.Shell")
Dim Fao :Set Fso = CreateObject("Scripting.FileSystemObject")
Dim Rex :Set Rex = new regexp
'-> Varibles Used At Run Time
Dim TsR, TsW, Tx, Vr
'-> Check To Make Sure File Exists
If Fso.FileExists("ScriptingSamples2.txt") Then
'-> Read All Contents Into One Varible
Set Ts = Fso.OpenTextFile("ScriptingSamples2.txt")
Vr = Ts.ReadAll
Ts.Close
'-> Create Text File To Write New Contents
Set Ts = Fso.CreateTextFile("Test_ScriptingSamples2.txt")
'-> Loop Threw The Varible
For Each Tx In Split(Vr, vbCrLf)
'-> Removes Blank Lines From New File
If Not Tx = "" Then
'-> Text Pattern Looks For 1, 2,Up To 99
Rex.Pattern ="(\d{1,2})"
'-> Not A Match Add It To New File
If Not Rex.Test(Tx) Then
Ts.WriteLine Tx
End If
End If
Next
Ts.Close
'-> Open Up The Contents Of The New File
Act.Run("Test_ScriptingSamples2.txt")
Else
MsgBox "Error :Missing This File : ScriptingSamples2.txt", _
4128,"Error No File Found"
End If

Rename Demo_Regex.vbs,txt to Demo_Regex.vbs to make active

Demo_Regex.vbs.txt

Share this post


Link to post
Share on other sites

That works to take those lines out, except how would I used regex to parse ScriptingSamples2.txt into multiple script files. Like in the text document I uploaded, each numbered section needs to be in it's own separate script file.

2. A script to fetch disk space on drive C:

Option Explicit

Const CONST_GB = 1073741824

Dim strComputer, objWMIService, objLogicalDisk, intFreeGB

strComputer = "."

Set objWMIService = GetObject("winmgmts://" & strComputer)

Set objLogicalDisk = objWMIService.Get("Win32_LogicalDisk.DeviceID='C:'")

intFreeGB = objLogicalDisk.FreeSpace / CONST_GB

Wscript.Echo "There are " & Round(intFreeGB,2) & " gigabytes of free disk space."

I would like that part in a script titles Script_2.vbs. So the script would not only parse the entire text document, but split each section into their own number corresponding vbs file as well.

Put ScriptingSamples2.txt in the same folder as this parse.txt, switch the parse.txt to parse.vbs and run it and see what happens. I need a script that does that except using regex

parse.txt

Share this post


Link to post
Share on other sites

I just had a quick look. It's not hard to do but fundamentally it doesn't feel like a job that really needs automating i.e. one that you'd do repeatedly. Even if it's simple to do, it'll take about as much time to write this as it would to do the job manually (there's no point in me spending 5 minutes to write a script that will save you 5 minutes of manual work just once). If you had data in this exact format to parse everyday then for sure, a script to split it would make a whole lot of sense.

Also, if someone feels like writing something, you also have to deal with stuff like this littered throughout the whole thing:

# End of Part 1

#2 File & Text Management

#3 Dates & Popups

#4 Registry

#5 Desktop Management

#6 Event Logs

#7 Controlling Applications

#8 WMI Services

#9 Miscellaneous

#End of File

Gisli Sigmundson - Course Supplement

VbScript Examples (All the examples are believed to be in the public domain)

Page 2 of 27

But since you're seemingly learning vbscript, why not try it yourself? You already have most of the required code contained in these samples i.e. how to read from and write to text files. The only real "challenge" you have left is figuring out on which line a new text section starts (you don't really need to use a regular expression for this either, simple string operations will do). Then by all means we'll give you a hand with your code if you run into any problems (for the sake of learning).

Share this post


Link to post
Share on other sites

Here I made some modification and the script run and produces the vbs files,

but it does not place the correct script info into each vbs, you will have to

work that out. Change the path for the files, to what you had.


textFile = "ScriptingSamples2.txt"
saveTo = "Script_"
writeTo = ""
' numberPattern = "^([0-9]|[1-9])$"
numberPattern = "(\d{1,2})"
dim fso,fileFrom,regex
set fso = CreateObject("Scripting.FileSystemObject")
set fileFrom = fso.OpenTextFile(textFile, 1)
set regex = new RegExp

regex.Pattern = numberPattern
regex.IgnoreCase = False
regex.Global = True

On Error Resume Next
Do while fileFrom.AtEndOfStream <> True
line = fileFrom.ReadLine
Set matches = regex.Execute(line)
If regex.Test(line) = True Then
writeTo = saveTo & matches(0).SubMatches(0) & ".vbs"
set fileTo = fso.CreateTextFile(writeTo)
ElseIf fso.FileExists(writeTo) Then
fileTo.WriteLine(line)
End If
Loop

Regex_Demo.vbs.txt

Share this post


Link to post
Share on other sites

@gunsmokingman thanks for the awesome help man, I got it to work and pull the proper contents.

The only differernce was that I changed the numberPattern from the one you had to this "^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$"

Share this post


Link to post
Share on other sites

Just a few points, if you really want to learn vbscript:

-using option explicit is a best practice. It cuts down on errors and typos. But that means you do have some more vars to declare: Dim textFile, saveTo, writeTo, fileTo, numberPattern, line, matches

-regular expressions are typically used for complex input validation (e.g. validating a postal code), or to extract specific content from a lot of data (e.g. getting the infos out of a specific tag in a HTML page), and not what's being done here. It's not typically your first option.

First, your regex is WAY over-complicated for nothing. The last part never matches anything, and there's no reason for all that grouping, or using [0-9] instead of \d. "^\d+" would suffice, and you wouldn't even have to use submatches then (just get rid of .SubMatches(0) and change the regex)

Then again, it would have been far simpler, quicker and easier to use simple string functions for this i.e. using a counter which is initialized to one, and then seeing if that counter's value is what the line starts with i.e. if instr(line, counter) = 1 then (increment the counter when there's a match). That's super simple and it actually works great... until you reach number 62 which doesn't exist in your text file, so it stops there understandably (62 is never found). Now, at this point, one could consider using regular expressions to match all numbers (in no particular order in a file with *many* irregularities) and using that to dump the relevant text.

-you should be explicitly closing the files which you open with CreateTextFile. In any programming language, when you open files, you typically close them after. You're lucky that the WSH closes them behind your back or you'd have like 75 files opened at once otherwise.

-there is another problem with inconsistencies in your text file: # 46 is there twice. So CreateTextFile fails silently (thanks to "on error resume next"). So it just keeps adding unrelated content to the previous file which you hadn't properly closed. Since both #46 follow each other, the second one ends up being in the same file as the first but if their ordering was different in the file it might have landed in any other file. The easiest fix here is still to correct the source/text file (otherwise you can test if the files already exist, and if they do add a suffix or similar).

Another option is to rename one of the 46's to 62 (making the file more consistent) and to use a very simple counter approach. Then that works just fine for the entire thing (no need for a regex).

-if fso.FileExists(writeTo) then always returns true and serves no actual purpose. if true then would do the same thing. You might as well just keep the else by itself.

-it's not exactly a problem with the script, but I guess it would have been nice to keep the "numbered" line, and adding it as a comment as the first line of the destination files. And also getting rid of lines starting with #. Both of which are easy to do.

Share this post


Link to post
Share on other sites

Thanks for the input, next time I will take that all into consideration. I try to do scripts without option explicit first and then go back and add it in if I do end up having any typos or the script isn't working. But I am very new to vbscript, never knew it existed until January, so again I appreciate the help and critique, thanks again :)

Share this post


Link to post
Share on other sites

You might want to look into PowerShell then. That's what's replaced VBScript.

Share this post


Link to post
Share on other sites

Yea, I'm actually in a class where we did batch files followed by vbscript which we just finished and moving to powershell this week.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...