/build/static/layout/Breadcrumb_cap_w.png

VBS to .INI Please help

Hello, Im pretty much a novice scriptor.  I was wondering is there a script that can find the environmental varialble for the current logged in user id, and output that ID to a string in an .ini file.  I have a .INI file that has a string that reads DataHome=C:\Users\USERID\Documents\StyleADVISOR\Data.  I need for USERID to be replaced with the current logged on users ID, Any help would be greatly appreciated.

1 Comment   [ + ] Show comment
  • No need to use this in a MSI?
    Because that makes life much easier.

    [LogonUser] property being used in an .INI. - jaybee96 10 years ago

Answers (3)

Answer Summary:
Posted by: spartacus 10 years ago
Black Belt
0

Something to start you off with at least, it modifies the file MyINI.ini in the root folder of C:\

Note: no error checking code has been included.


Const ForReading = 1
Const ForWriting = 2

Dim sTextToSubstitute, sReplaced, sText
Dim oWshShell, oFSO, oFile

Set oWSH                = CreateObject( "WScript.Shell" )
Set oFSO                = CreateObject("Scripting.FileSystemObject")
Set oFile               = oFSO.OpenTextFile("C:\MyIni.ini", ForReading)

sText = oFile.Readall
oFile.close

sTextToSubstitute =oWSH.ExpandEnvironmentStrings( "%USERNAME%" )
sTextToModify     ="DataHome=C:\Users\USERID\Documents\StyleADVISOR\Data"
sReplaced         = Replace(sText,"USERID",sTextToSubstitute)

Set oFile         = oFSO.OpenTextFile("C:\MyIni.Ini", ForWriting)
oFile.WriteLine sReplaced
oFile.Close

msgbox sReplaced


Regards,

Spartacus




Comments:
  • Thank you very very much Spartacus this really helped. - bpriestl 10 years ago
Posted by: mramsdell 10 years ago
Orange Senior Belt
0

You can also do this in Powershell. 

create a batch file that has the following:

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command "& {(Set-ExecutionPolicy -ExecutionPolicy Unrestricted) }

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe .\replace.ps1


create a file called replace.ps1 and have the following replacing the location and name of the INI file.:

(Get-Content C:\inifiles\Test.ini ) |
Foreach-Object {$_ -replace "USERID", [Environment]::UserName} |
Set-Content C:\inifiles\Test.ini


Posted by: anonymous_9363 10 years ago
Red Belt
0
What happened to the 'CODE' button?!?!?

For VBS users, here's a rather good INI class file:

'// To work with an INI file, first 'open' it.
'// The OpenINIFile Function reads the INI file into a dictionary object.
'// The class is then ready for operations. The file itself is not open but as long as
'// OpenINIFile has been successfully called the class will hold the file in memory as a
'// dictionary object and any number of operations can be performed.
'//                          
'// blnResult = OpenINIFile(FilePath)      Returns Boolean    True if file opened successfully
'//                          
'// Call CloseINIFile()         Sub to close INI file after use.
'//                    This sets the dictionary to Nothing.
'//                    The INI file itself isn't actually open
'//                    so CloseINIFile isn't strictly required.
'//                    If another file is opened the dictionary will be set to Nothing
'//                    before proceeding. If the Class is Set to Nothing the dictionary
'//                    will also be cleared.
'//                          
'//  NOTE ABOUT ERROR CODES
'// The error codes are designed to relate to the same thing regardless of the function.
'//    0     Success
'//    1     The key does not exist, regardless of whether you're trying to read from or delete the key.
'//     2     Relates to the section.
'//        For functions that require a section, it means the section does not exist.
'//        When trying to write a new section it means the section already exists.
'//     3     No file has been 'opened'
'//     4     Any other error condition, indicating that there was an unexpected problem.
'//
'//                          
'// ____________________ START INI Class HERE ________________________________________

Class clsINI

    Private objFSO_INI
    Private objINFile
    Private objINIDictionary
    Private strINIFile
    Private strSeparator

    Private Sub Class_Initialize()
        Set objFSO_INI             = CreateObject("Scripting.FileSystemObject")
        strSeparator             = Chr(149)
     End Sub

      Private Sub Class_Terminate()
        Set objFSO_INI             = Nothing
        Set objINIDictionary         = Nothing
      End Sub

      '// Function to Read INI file into objINIDictionary
      Public Function OpenINIFile(ByVal strINI)
        Dim objLine
        Dim strSection
        Dim strList
       
        strINIFile             = strINI
       
        If objFSO_INI.FileExists(strINIFile) = False Then
            OpenINIFile         = False
            Exit Function
        End If
       
        strINIFile             = strINIFile
       
        '// Reset objINIDictionary in case an earlier file wasn't closed with CloseINIFile
        Set objINIDictionary         = Nothing


        '// Read INI file into dictionary object. Each section will be a key.
        '// Section key/value pairs will be added as objINIDictionary.Key item
        '// After the file is read there will be one objINIDictionary.Key for each section header.
        '// Each key item will be a string of key/value pairs separated by strSeparator characters.

        Set objINIDictionary         = CreateObject("Scripting.Dictionary")
        objINIDictionary.Add "Glo_bal", strSeparator

        On Error Resume Next
        Set objINFile             = objFSO_INI.OpenTextFile(strINIFile, 1) 
       
        Do While objINFile.AtEndOfStream = False
            objLine         = objINFile.ReadLine
            objLine         = Trim(objLine)
            If Len(objLine) > 0 Then
                If Left(objLine, 1) = "[" Then
                    strSection = objLine
                    objINIDictionary.Add strSection, strSeparator
                ElseIf objINIDictionary.Exists(strSection) Then
                    strList = objINIDictionary.Item(strSection)
                    strList = strList & objLine & strSeparator
                    objINIDictionary.Item(strSection) = strList
                Else '// global comment at top. If no objINIDictionary.Key strSection exists Then no sections have been read yet.
                    strList = objINIDictionary.Item("Glo_bal")
                    strList = strList & objLine & strSeparator
                    objINIDictionary.Item("Glo_bal") = strList
                End If   
            End If   
        Loop
       
        objINFile.Close 
        Set objINFile             = Nothing
        OpenINIFile             = True
    End Function

    '// Close an open INI file. The file is not actually open but it's closed
    '// for the purposes of this class by setting objINIDictionary = Nothing.

    Public Sub CloseINIFile()
        Set objINIDictionary         = Nothing
    End Sub

    '// =========================================================================================================
    '//     Name:    GetSectionNames
    '//  Purpose:    Retrieves section names
    '//  Example:     blnResult = Cls.GetSectionNames()
    '//    Input:    None
    '//   Output:    UBound of array is 0 and array(0) is ""        no file open, or no sections in file
    '//        Array populated                    file section names returned in the array
    '//  Returns:    True/False
    '// =========================================================================================================
    Public Function GetSectionNames()
        Dim arrSection
        Dim intIndex
        Dim strTemp
        Dim strSection
       
        If IsObject(objINIDictionary) = False Then
            arrSection         = Array("")
            GetSectionNames     = arrSection  '// No file open
            Exit Function
        End If

        If objINIDictionary.Count = 0 Then
            arrSection         = Array("")
            GetSectionNames     = arrSection  '// No keys
            Exit Function
        End If

        On Error Resume Next
        arrSection             = objINIDictionary.Keys
        For intIndex = 0 to UBound(arrSection)
            strTemp         = arrSection(intIndex)
            If (strTemp <> "Glo_bal") Then
                strTemp     = Mid(strTemp, 2, (len(strTemp) - 2))
                strSection     = strSection & (strTemp & strSeparator)
            End If  
        Next  
       
        GetSectionNames         = Split(strSection, strSeparator)
    End Function

    '// =========================================================================================================
    '//     Name:    GetINIValue(Section, Key, Value)
    '//  Purpose:    Retrieves value from a key
    '//    Input:    Section            The section name containing the key
    '//        Key            The key name
    '//       
    '//   Output:    Value            A ByRef variable to store the value
    '//  Returns:    0            Data returned
    '//        1            No such key
    '//        2            No such section
    '//        3            Unexpected error in text of file
    '// =========================================================================================================
    Public Function GetINIValue(ByVal strSection, ByVal strKey, ByRef strValue)
        Dim strSectionLine
        Dim intPos1
        Dim intPos2
        Dim strItem
        Dim intLenStrItem

        Select Case CheckBasics(strSection)
            Case 3
                GetINIValue     = 3      '// No file open
                Exit Function
            Case 2
                GetINIValue     = 2      '// No such section
                Exit Function
        End Select

        strValue             = ""
        strSectionLine             = objINIDictionary.Item(strSection)
        strItem             = strSeparator & strKey & "="
        intLenStrItem             = Len(strItem)

        intPos1             = InStr(1, strSectionLine, strItem, 1)
        If intPos1 = 0 Then
            strValue         = ""
            GetINIValue         = 1      '// No such key
            Exit Function
        End If

        intPos2             = InStr((intPos1 + intLenStrItem), strSectionLine, strSeparator, 1)
        If intPos2 = 0 Then
            GetINIValue         = 4     '// Unexpected error
        ElseIf intPos2 = (intPos1 + 1) Then    '// Key exists but value is ""
            GetINIValue         = 0
        Else
            strValue         = Mid(strSectionLine, (intPos1 + intLenStrItem), (intPos2 - (intPos1 + intLenStrItem)))
            GetINIValue         = 0
        End If 
      End Function

    '// =========================================================================================================
    '//     Name:    GetSectionValues(strSection, arrArray)
    '//  Purpose:    Retrieves key/value pairs from a section
    '//    Input:    strSection        The section name
    '//   Output:    arrArray        A ByRef array of key/value pairs
    '//  Returns:    0            Data returned
    '//        1            No such key
    '//        2            No such section
    '//        3            No file open
    '//        4            Unexpected error in text of file
    '// =========================================================================================================
    Public Function GetSectionValues(Byval strSection, ByRef arrValues)
        Dim arrItem
        Dim arrNewItem()
        Dim intIndex
        Dim intNewIndex
       
        Select Case CheckBasics(strSection)
            Case 3
                GetSectionValues = 3  '// No file open
                Exit Function
            Case 2
                GetSectionValues = 2  '// No such section
                Exit Function
        End Select

        arrItem = Split(objINIDictionary.Item(strSection), strSeparator)

        '// Go through arrItem, weeding out comments.
        '// Any non-comment can be added to arrNewItem
           intNewIndex             = 0
       
        For intIndex = 0 to UBound(arrItem)
            If Left(arrItem(intIndex), 1) <> ";" Then
                ReDim Preserve arrNewItem(intNewIndex)
                arrNewItem(intNewIndex) = arrItem(intIndex)
                intNewIndex         = (intNewIndex + 1)
            End If
        Next  

        arrValues             = arrNewItem     
       
        GetSectionValues         = 0
    End Function

    '// =========================================================================================================
    '//     Name:    WriteINIValue(Section, Key, Value)
    '//  Purpose:    Writes a value to a key.
    '//        'Section' and 'Key' will be written if necessary
    '//    Input:    Section            The section name
    '//        Key            The key name
    '//        Value            The data to write into the key
    '//   Output:    None
    '//  Returns:    0            Success
    '//        1            No such key
    '//        2            No such section
    '//        3            No file open
    '//        4            Unexpected error in text of file
    '// =========================================================================================================
      Public Function WriteINIValue(ByVal strSection, ByVal strKey, ByVal strValue)
        Dim strSectionLine
        Dim intPos1
        Dim intPos2
        Dim strItem
        Dim intLenStrItem

        Select Case CheckBasics(strSection)
            Case 3
                WriteINIValue     = 3  '// No file open
                Exit Function
            Case 2
                '// If section does not exist, write section and key=value, then quit:
                strSectionLine = strSeparator & strKey & "=" & strValue & strSeparator
                objINIDictionary.Add strSection, strSectionLine
                Call WriteNewINI
                WriteINIValue     = 0
                Exit Function
        End Select

        '// Section exists, get section values
        strSectionLine             = objINIDictionary.Item(strSection)
        strItem             = strSeparator & strKey & "="
        intLenStrItem             = Len(strItem)
        intPos1             = InStr(1, strSectionLine, strItem, 1)

        '// If strKey doesn't already exist, write it and quit
        If intPos1 = 0 Then
            strSectionLine         = strSectionLine & strKey & "=" & strValue & strSeparator
            objINIDictionary.Item(strSection) = strSectionLine
            Call WriteNewINI
            WriteINIValue         = 0
        Else  
            '// strKey exists. Snip out existing value from strSectionLine
            '// and rebuild string, adding new value
            intPos2         = InStr((intPos1 + intLenStrItem), strSectionLine, strSeparator)
            If intPos2 <> 0 Then
                If (intPos2 + 1) < Len(strSectionLine) Then  '// If Not last value in section, Get left up to "=" & value & right from bullet:
                    strSectionLine = (Left(strSectionLine, ((intPos1 + intLenStrItem) - 1))) & strValue & (Right(strSectionLine, (Len(strSectionLine) - (intPos2 - 1))))
                Else  '// Last value in section
                    strSectionLine =  (Left(strSectionLine, ((intPos1 + intLenStrItem) - 1))) & strValue & strSeparator
                End If   
               
                objINIDictionary.Item(strSection) = strSectionLine
                Call WriteNewINI
                WriteINIValue     = 0
            Else
                WriteINIValue     = 4 '// Unexpected error
                Exit Function
            End If     
         End If
       End Function

    '// =========================================================================================================
    '//     Name:    DeleteINIValue(Section, Key)
    '//  Purpose:    Deletes a value from a key.
    '//    Input:    Section            The section name
    '//        Key            The key name
    '//        Value            The data to write into the key
    '//   Output:    None
    '//  Returns:    0            Success
    '//        1            No such key
    '//        2            No such section
    '//        3            No file open
    '//        4            Unexpected error in text of file
    '//          For this Function success would be if the return value < 3
    '// =========================================================================================================
    Public Function DeleteINIValue(ByVal strSection, ByVal strKey)
        Dim strSectionLine
        Dim intPos1
        Dim intPos2
        Dim strItem
       
        Select Case CheckBasics(strSection)
            Case 3
                DeleteINIValue     = 3  '// No file open
                Exit Function
            Case 2
                DeleteINIValue     = 2  '// No such section
                Exit Function
        End Select

        strSectionLine             = objINIDictionary.Item(strSection)
        strItem             = strSeparator & strKey & "="
        intPos1             = InStr(1, strSectionLine, strItem, 1)
        If intPos1 = 0 Then
            DeleteINIValue         = 1      '// No such key
            Exit Function
        End If

        intPos2             = InStr((intPos1 + 1), strSectionLine, strSeparator, 1)
        If intPos2 = 0 Then 
            DeleteINIValue         = 4  '// Unexpected error
            Exit Function
        Else
            strSectionLine         = (Left(strSectionLine, (intPos1))) & (Right(strSectionLine, (Len(strSectionLine) - intPos2)))
            objINIDictionary.Item(strSection) = strSectionLine
            Call WriteNewINI
            DeleteINIValue         = 0
        End If
    End Function

    '// =========================================================================================================
    '//     Name:    WriteINISection(Section)
    '//  Purpose:    Write a new section
    '//    Input:    Section            The section name
    '//   Output:    None
    '//  Returns:    0            Success
    '//        1            No such key
    '//        2            Section already exists
    '//        3            No file open
    '//        4            Unexpected error in text of file
    '//          For this Function success would be if the return value < 3
    '// =========================================================================================================
    Public Function WriteINISection(ByVal strSection)
        Select Case CheckBasics(strSection)
            Case 3
                WriteINISection = 3  '// No file open
            Case 2
                objINIDictionary.Add strSection, strSeparator
                Call WriteNewINI
                WriteINISection = 0
            Case Else
                WriteINISection = 2 '// Section already exists
        End Select
    End Function  

    '// =========================================================================================================
    '//     Name:    DeleteINISection(ByVal strSection) 
    '//  Purpose:    Delete a section
    '//    Input:    strSection        The section name
    '//   Output:    None
    '//  Returns:    0            Success
    '//        1            No such key
    '//        2            No such section
    '//        3            No file open
    '//        4            Unexpected error in text of file
    '//          For this Function success would be if the return value < 3
    '// =========================================================================================================
    Public Function DeleteINISection(ByVal strSection)

        Select Case CheckBasics(strSection)
            Case 3
                DeleteINISection = 3  '// No file open
            Case 2
                DeleteINISection = 2  '// No such section
            Case Else
                objINIDictionary.Remove strSection
                Call WriteNewINI
                DeleteINISection = 0
         End Select

    End Function   

    '// An internally-called Sub to update INI file after writing new value or adding section.
    '// It won't be called unless a file is "open", in which case the file path is valid
    '// and objINIDictionary is not Nothing, so just set attributes to 0 and write the new INI file.
    '// NB:
    '// This has not been tested with system INIs under Windows versions which have system file protection!
    Private Sub WriteNewINI()
        Dim objFileAttributes
        Dim objFile
        Dim arrKeys
        Dim intIndex
        Dim strLine
        Dim strItem
        Dim strItem2
        Dim strGlobal
       
        On Error Resume Next
        '// Remove attributes such as read-only and save current attributes
        Set objFile             = objFSO_INI.GetFile(strINIFile)
        objFileAttributes         = objFile.Attributes
        objFile.Attributes         = 0
        Set objFile             = Nothing

        arrKeys = objINIDictionary.Keys
        For intIndex = 0 to UBound(arrKeys)
            strItem         = arrKeys(intIndex)
            If strItem = "Glo_bal" Then
                strGlobal     = objINIDictionary.Item(strItem)
                strGlobal     = Replace(strGlobal, strSeparator, vbCRLF)
                strGlobal     = strGlobal & vbCRLF
            Else  
                strItem2     = objINIDictionary.Item(strItem)
                strItem2     = Replace(strItem2, strSeparator, vbCRLF)
                strLine     = strLine & strItem & strItem2 & vbCRLF
            End If  
        Next

        strLine             = strGlobal & strLine '// Add in global comments section

        objFSO_INI.DeleteFile strINIFile, True

        Set objINFile             = objFSO_INI.CreateTextFile(strINIFile)    
        objINFile.Write strLine
        objINFile.Close
        Set objINFile             = Nothing

        Set objFile             = objFSO_INI.GetFile(strINIFile)
        objFile.Attributes         = objFileAttributes
        Set objFile             = Nothing  

       End Sub

    '// An internally-called function to check for objINIDictionary instantiation and section existence.
    '// It also does the work of putting [ ] around the section name sent in.
    '// It's here to save a few lines, so that other functions don't have to be re-written
    '// for each method in the class
    Private Function CheckBasics(strSection)
        If IsObject(objINIDictionary) = False Then
            CheckBasics         = 3  '// No file open
            Exit Function
        End If

        If (Left(strSection, 1) <> "[") Then
            strSection         = "[" & strSection
        End If
       
        If (Right(strSection, 1) <> "]") Then
            strSection         = strSection & "]"
        End If

        If objINIDictionary.Exists(strSection) = False Then
            CheckBasics         = 2
        Else
            CheckBasics         = 0
        End If
    End Function
    
End Class

 
This website uses cookies. By continuing to use this site and/or clicking the "Accept" button you are providing consent Quest Software and its affiliates do NOT sell the Personal Data you provide to us either when you register on our websites or when you do business with us. For more information about our Privacy Policy and our data protection efforts, please visit GDPR-HQ