Question

How to write GUID to .ini file using vbscript?

guid = CreateGUID()
WriteIni "testsection", "ID", guid, "H:\test123.ini"        
Function CreateGUID()
    CreateGUID = ""
    Set objTypeLib = CreateObject("Scriptlet.TypeLib")
    Wscript.Echo "GUID: " & objTypeLib.Guid
    CreateGUID = objTypeLib.Guid
End Function

The above code is not working properly it appends some other character to the GUID of .ini file. For example:

After writing GUID to test123.ini:

[testsection]
ID=EAE11CC4-F60E-4B21-8AA8-E0CE2ADE5521 5

Here extra character(ex: 5 ) was added. It has to update the file like this:

[testsection]
ID=EAE11CC4-F60E-4B21-8AA8-E0CE2ADE5521
Was it helpful?

Solution

It's a known bug in the Scriptlet.TypeLib object. The Guid property should be 38 characters long, but comes back with a length of 40 with 2 garbage characters at the end. You need to trim the Guid value to avoid the issue:

Function CreateGUID()
  CreateGUID = ""
  Set objTypeLib = CreateObject("Scriptlet.TypeLib")
  CreateGUID = Left(TypeLib.Guid, 38)     ' With curly braces: {47BC69BD-06A5-4617-B730-B644DBCD40A9}
  ' CreateGUID = Mid(TypeLib.Guid, 2, 36) ' Without curly braces: 47BC69BD-06A5-4617-B730-B644DBCD40A9
End Function

OTHER TIPS

You're making this more complicated than it needs to be. I'd suggest to read the INI file into a dictionary of dictionaries, so that a file like this:

[Section1]
value1="foo"
value2="bar"

[Section2]
valueX="baz"

becomes a data structure like this:

+-Section1
| +-value1 -> "foo"
| `-value2 -> "bar"
`-Section2
  `-valueX -> "baz"

Then you can simply add a GUID to a given section like this:

section = "Section1"

If Not ini.Exists(section) Then
  ini.Add section, CreateObject("Scripting.Dictionary")
End If

ini(section)("ID") = CreateObject("Scriptlet.TypeLib").GUID

and write the data back to a file like this:

Set fso = CreateObject("Scripting.FileSystemObject")

Set f = fso.OpenTextFile("C:\path\to\your.ini", 2)
For Each section In ini.Keys
  f.WriteLine "[" & section & "]"
  For Each value In ini(section).Keys
    f.WriteLine value & "=" & Chr(34) & ini(section)(value) & Chr(34)
  Next
  f.WriteLine
Next
f.Close

A while back I wrote a procedure (ParseIni) for parsing INI files into such data structures.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top