Solved

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

Posted on 2014-02-15
7
2,703 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
Comment Utility
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
Comment Utility
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
Comment Utility
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 to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 51

Assisted Solution

by:Bill Prew
Bill Prew earned 200 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks guys, both solutions worked great
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

I met Paul Devereux (@pdevereux) today when I responded to his tweet asking “Anybody know how to automate adding files from disk to a folder in #outlook  ?”.  I replied back and told Paul that using automation, in this case scripting, to add files t…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now