0
votes

I am creating a script that will contain variables that need to be set by the user. I created an ini file where those variables can be defined by the user without having to mess with the script itself. I need the VBS script to be able to read the file and create a variable based on the first part of the line and then set the value of that variable based on the second part of that line.

The ini file looks something like this

path=C:\users\whatever
filename=whatever.txt
FileTypes=txt,doc,mp3,etc

In a batch file, this is easy, you can simply do:

for /f "delims=" %%x in (config.ini) do (set "")

I would love if there is an equally simple answer in VBS, but here is what I have (working)

filename = "config.ini"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
  LineArray = Split(f.ReadLine , "=")
    Select Case LineArray(0)
        Case "path"
            path = LineArray(1)
        Case "filename"
            fname = LineArray(1)
        Case "FileTypes"
            FileTypes = LineArray(1)
    End Select
Loop

f.Close

This works, but I essentially had to rename my variables myself, and the script is more difficult to maintain and not as efficient.

It would be nice if I could replace the case statement with something more like

DIM "LineArray(0)"=LineArray(1)

and have VBS recognize that LineArray(0) should be defined as a new variable using the value of LineArray(0) as the name of the variable.

Is there a way to do this in VBS?

2

2 Answers

1
votes

Execute (or ExecuteGlobal) will do what you want with the input you described. I would advise caution, though, because these statements will not only define variables, but execute any code passed into them. Using a dictionary is a safer approach:

Set ini = CreateObject("Scripting.Dictionary")

Do Until f.AtEndOfStream
  line = f.ReadLine
  If InStr(line, "=") > 0 Then
    arr = Split(line, "=", 2)
    ini(Trim(arr(0))) = arr(1)
  End If
Loop

WScript.Echo ini("path")

Particularly if you want to handle actual INI files, which may consist of several sections (and also contain comments):

[section1]
foo = "something"
bar = 42

[section2]
;this is a comment
foo = "something"
baz = 23

I wrote such an INI parser myself a couple years ago. You can find it on my blog.

0
votes

I figured it out. The answer is Execute. The simple line I needed was:

Execute(LineArray(0) + " = " + "LineArray(1)")