Solved

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

Posted on 2014-02-15
7
2,903 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
  • 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
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

 
LVL 54

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

I hope you'll find this tutorial useful and interesting. So let's try to extend Tcl with a new package.  For anyone more deeply interested please check out the book "Practical Programming in Tcl and Tk". It's really one of the best written books abo…
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

679 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