Solved

VBS/HTA - Read ini/txt file and get specific variable from specific secion

Posted on 2014-02-15
7
3,047 Views
Last Modified: 2014-03-10
Hi EEs,

Any help with resolving the following is much appreciated...

This will be used in an HTA app so all syntax must work within hta.

I need a script to prompt user for numeric input of 4 digits. This would be the '[Section]' in the (attached) ini file. Then the script should grab the values of the two 'Keys' in that specific section and assign them to specific variables.

(I then plan to map a drive using both the variables)

I have posted (attached vbs) what I have so for (with attempt to assign one variable), but it does not work :(
t.ini
Test-EE.vbs
0
Comment
Question by:BigBadWolf_000
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 20

Expert Comment

by:ltlbearand3
ID: 39861452
Because your data is on multiple lines, I recommend using the instr function to search the file for the data you need instead of looping through the file.  This way you can get the position in the file to look for the data.  Here is the adjusted code.

I also put in a loop to make sure they enter a four digit number.  Granted the code will just say the share was not found if they enter something else, but this just loops until the get a good starting point.

I like DevGuru to find out how vbscript syntax works.  Check it out for more details -Dev Guru Instr

If you are using hta, you could also change your input box to be more of a browser look, but I just left that alone for now as you can get more complicated with that.
Test-EE.vbs
0
 
LVL 14

Author Comment

by:BigBadWolf_000
ID: 39861649
Thanks ltlbearand3: Goog to know of the instr function, however when....

 5678 is entered it displays the whole key (unc=\\xyz\ShareNameZ), I need to show only (\\xyz\ShareNameZ)

1234 is entered it returns "Share not found"

9123 is entered, it errors out...
Line:      24
Char:      2
Error:      Invalid procedure call or argument: 'Mid'
Code:      800A0005
Source:       Microsoft VBScript runtime error
0
 
LVL 20

Expert Comment

by:ltlbearand3
ID: 39862015
Sorry about that, I forgot to move past the UNC= after we find the position (which is the start of the found string).  I also forgot to account for the end of the file.  Try this code:
Const ForReading = 1

' Specify the file name.
strFile = "C:\Users\Us\Desktop\t.ini"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile, ForReading)

' Simple Check to make sure we have a four digit number
Do While len(strSection) <> 4
	strSection = InputBox("Enter Section Name [4 Digit #]", "Test")
Loop

'Read the full file
strData = objFile.ReadAll

' Find the position of the string for which we are looking
strPosition = instr(strData, "[" & strSection & "]")

If strPosition > 1 Then
	' We found something.  Now look for "unc="
	strUNCPosition = instr(strPosition, strData, "unc=") + 4
	
	' Now get the next carriage return / line feed
	strEndUNC = instr(strUNCPosition, strData, vbcrlf)
	
	' If we did not find a cr/lf then use the length of the file plus one to get the last letter.
	If strEndUNC = 0 then strEndUNC = len(strData)+1
	
	' Now parse out the share name
	strShare = Mid(strData, strUNCPosition, strEndUNC - strUNCPosition)
End If

' Clean up.
objFile.Close

' Display result.
If len(strShare) = 0 Then
  Wscript.Echo "Share not found"
Else
  Wscript.Echo "Share: " & strShare
End If

Open in new window

0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 56

Assisted Solution

by:Bill Prew
Bill Prew earned 200 total points
ID: 39863766
Give this a try, it puts the logic to read keys from an INI in a function for easier use.

' Specify the file name.
strFile = "C:\Users\Us\Desktop\t.ini"

' Prompt for section
strSection = InputBox("Enter Section Name", "Test")

' Ket keys from INI file
strPointer = ReadIni(strFile, strSection, "pointer")
strShare = ReadIni(strFile, strSection, "unc")

' Display result.
If (strShare = "") Then
  Wscript.Echo "Share not found"
Else
  Wscript.Echo "Share: " & strShare
End If


Function ReadIni( myFilePath, mySection, myKey )
    ' This function returns a value read from an INI file
    '
    ' Arguments:
    ' myFilePath  [string]  the (path and) file name of the INI file
    ' mySection   [string]  the section in the INI file to be searched
    ' myKey       [string]  the key whose value is to be returned
    '
    ' Returns:
    ' the [string] value for the specified key in the specified section
    '
    ' CAVEAT:     Will return a space if key exists but value is blank
    '
    ' Written by Keith Lacelle
    ' Modified by Denis St-Pierre and Rob van der Woude

    Const ForReading   = 1
    Const ForWriting   = 2
    Const ForAppending = 8

    Dim intEqualPos
    Dim objFSO, objIniFile
    Dim strFilePath, strKey, strLeftString, strLine, strSection

    Set objFSO = CreateObject( "Scripting.FileSystemObject" )

    ReadIni     = ""
    strFilePath = Trim( myFilePath )
    strSection  = Trim( mySection )
    strKey      = Trim( myKey )

    If objFSO.FileExists( strFilePath ) Then
        Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False )
        Do While objIniFile.AtEndOfStream = False
            strLine = Trim( objIniFile.ReadLine )

            ' Check if section is found in the current line
            If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                strLine = Trim( objIniFile.ReadLine )

                ' Parse lines until the next section is reached
                Do While Left( strLine, 1 ) <> "["
                    ' Find position of equal sign in the line
                    intEqualPos = InStr( 1, strLine, "=", 1 )
                    If intEqualPos > 0 Then
                        strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                        ' Check if item is found in the current line
                        If LCase( strLeftString ) = LCase( strKey ) Then
                            ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) )
                            ' In case the item exists but value is blank
                            If ReadIni = "" Then
                                ReadIni = " "
                            End If
                            ' Abort loop when item is found
                            Exit Do
                        End If
                    End If

                    ' Abort if the end of the INI file is reached
                    If objIniFile.AtEndOfStream Then Exit Do

                    ' Continue with next line
                    strLine = Trim( objIniFile.ReadLine )
                Loop
            Exit Do
            End If
        Loop
        objIniFile.Close
    Else
        WScript.Echo strFilePath & " doesn't exists. Exiting..."
        Wscript.Quit 1
    End If
End Function

Open in new window

~bp
0
 
LVL 14

Author Comment

by:BigBadWolf_000
ID: 39901646
Thanks ltlbearand3: However, when you enter 1234 it returns the 'Share not found'. I am sorry for the delay in responding.

Thanks billprew: will test your script today
0
 
LVL 20

Accepted Solution

by:
ltlbearand3 earned 300 total points
ID: 39915092
I had a problem with my logic.  Try this.

Const ForReading = 1

' Specify the file name.
strFile = "C:\Users\Us\Desktop\t.ini"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile, ForReading)

' Simple Check to make sure we have a four digit number
Do While len(strSection) <> 4
	strSection = InputBox("Enter Section Name [4 Digit #]", "Test")
Loop

'Read the full file
strData = objFile.ReadAll

' Find the position of the string for which we are looking
strPosition = instr(strData, "[" & strSection & "]")

If strPosition > 0 Then
	' We found something.  Now look for "unc="
	strUNCPosition = instr(strPosition, strData, "unc=") + 4
	
	' Now get the next carriage return / line feed
	strEndUNC = instr(strUNCPosition, strData, vbcrlf)
	
	' If we did not find a cr/lf then use the length of the file plus one to get the last letter.
	If strEndUNC = 0 then strEndUNC = len(strData)+1
	
	' Now parse out the share name
	strShare = Mid(strData, strUNCPosition, strEndUNC - strUNCPosition)
End If

' Clean up.
objFile.Close

' Display result.
If len(strShare) = 0 Then
  Wscript.Echo "Share not found"
Else
  Wscript.Echo "Share: " & strShare
End If

Open in new window

0
 
LVL 14

Author Closing Comment

by:BigBadWolf_000
ID: 39919190
Thanks guys, both solutions worked great
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is pretty cool.  The purpose of this VB Script is to help you document where JAR (Java ARchive) files and specifically java class files are located so that you can address issues seen with a client or that you can speak intelligently with a dev…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question