How Can I Create a GUID Using a Script?
Hey, Scripting Guy! We have items that we need to track using unique identification numbers. My boss suggested that we use GUIDs for this purpose. Is there any way to create a GUID using a script?
Hey, DX. GUIDs (globally unique identifiers) are a good choice for a job like this; we don’t pretend to understand the algorithm behind GUIDs, but you are all-but-guaranteed that every GUID you generate will be unique. Although it’s theoretically possible to generate a duplicate GUID, it’s also theoretically possible that Bill Gates will give all his money to the Scripting Guys. We aren’t going to lose any sleep over either possibility.
There’s actually a very easy way to generate GUIDs, although it almost seems like cheating. (Hey, we said almost.) The Scriptlet.TypeLib object is designed to help you create Windows Script Components (basically a way of taking a script you wrote and making it act like a COM object). The Scriptlet.Typelib object includes a method that generates GUIDs for use with Windows Script Components type libraries; however, there’s no reason you can’t use this method to generate a GUID for other purposes. (After all, a GUID is a GUID is a GUID.) If you need a GUID, here’s a two-line script that will supply you with one:
Set TypeLib = CreateObject("Scriptlet.TypeLib") Wscript.Echo TypeLib.Guid
Not bad, huh? Of course, this script merely echoes the GUID back in a message box; if you want to actually use that GUID somewhere else, you’ll have to type it in. That might be OK if it wasn’t for the fact that GUIDs look like this:
And so, being the generous, self-serving guys that we are, we modified the script a bit. This script generates a GUID but then, instead of displaying that GUID in a message box, copies the GUID to the Clipboard:
Set TypeLib = CreateObject("Scriptlet.TypeLib") strGUID = TypeLib.Guid Set objIE = CreateObject("InternetExplorer.Application") objIE.Navigate("about:blank") objIE.document.parentwindow.clipboardData.SetData "text", strGUID objIE.Quit
If you’re wondering how we do that, well, we’re cheating once again. VBScript can’t copy items to the Clipboard, but Internet Explorer can. So we’re simply generating a GUID and then storing that value in a variable named strGUID. We then create an invisible instance of Internet Explorer, and use the clipboardData.SetData method to copy that GUID to the clipboard. That’s what we do in this line of code:
objIE.document.parentwindow.clipboardData.SetData "text", strGUID
We quit Internet Explorer, and now are free to go paste that GUID in anywhere we want to use it.