Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-02-15
7
Medium Priority
?
3,208 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 57

Assisted Solution

by:Bill Prew
Bill Prew earned 800 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 1200 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

When it comes to writing scripts for a Client/Server computing environment it is essential to consider some way of enabling the authentication functionality within a script. This sort of consideration mainly comes into the picture when we are dealin…
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

670 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