32

I want to generate GUID strings in VBScript. I know that there's no built-in function in VBScript for generating one. I don't want to use random-generated GUIDs. Maybe there is an ActiveX object that can be created using CreateObject() that is sure to be installed on (newer) Windows versions that can generate a GUID?

vividos
  • 6,468
  • 9
  • 43
  • 53
  • 2
    I think the accepted answer has much lower quality than the [highest voted one](http://stackoverflow.com/a/968790/2932052). Maybe a reason to rethink your decision? – Wolf Dec 07 '16 at 08:47

4 Answers4

57
Function CreateGUID
  Dim TypeLib
  Set TypeLib = CreateObject("Scriptlet.TypeLib")
  CreateGUID = Mid(TypeLib.Guid, 2, 36)
End Function

This function will return a plain GUID, e.g., 47BC69BD-06A5-4617-B730-B644DBCD40A9.

If you want a GUID in a registry format, e.g., {47BC69BD-06A5-4617-B730-B644DBCD40A9}, change the function's last line to

CreateGUID = Left(TypeLib.Guid, 38)
Helen
  • 87,344
  • 17
  • 243
  • 314
  • 2
    Best answer: combines providing a not too smart function and adding additional material for information about the details. This should be the accepted answer. – Wolf Dec 07 '16 at 08:44
  • Worked best for me. – Moir Apr 13 '21 at 01:47
34

How Can I Create a GUID Using a Script? (in: Hey, Scripting Guy! Blog) says this:

Set TypeLib = CreateObject("Scriptlet.TypeLib")
Wscript.Echo TypeLib.Guid

However, note that Scriptlet.TypeLib.Guid returns a null-terminated string, which can cause some things to ignore everything after the GUID. To fix that, you might need to use:

Set TypeLib = CreateObject("Scriptlet.TypeLib")
myGuid = TypeLib.Guid
myGuid = Left(myGuid, Len(myGuid)-2)
Wscript.Echo myGuid
Community
  • 1
  • 1
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
  • Thanks! I like the "Hey, Scripting Guy!" link! – vividos Jun 09 '09 at 21:50
  • 12
    For anyone using this method, be aware that the `Scriptlet.TypeLib` object will return _the same GUID_ each time you invoke the `GUID` property. If you need to generate multiple GUIDs, destroy and recreate the `Scriptlet.TypeLib` object or, better yet, wrap it in a function like others have shown so the object is created and destroyed with each function call. – Bond Jun 29 '15 at 21:03
  • @vividos broken link is fixed now (thanks to Google) – Wolf Dec 07 '16 at 08:52
9
' Returns a unique Guid on every call. Removes any cruft.
Function CreateGuid()
    CreateGuid = Left(CreateObject("Scriptlet.TypeLib").Guid,38)
End Function
BSalita
  • 8,420
  • 10
  • 51
  • 68
2
Set tlib = Server.CreateObject("Scriptlet.TypeLib")
strGuid = tlib.Guid
BobbyShaftoe
  • 28,337
  • 7
  • 52
  • 74