Thursday, February 25, 2010

Generating GUIDs with Powershell

Something I ran across the other day, was to use Powershell to generate a GUID.
This is quite useful since you’re not always working in a .NET application when you need one. And you don’t always want to compile an application to get it. 

One way to do this, is to talk to the .NET runtime in Powershell.  You can simply execute the following command :

[System.Guid]::NewGuid()

This will generate a simple Guid, however now you will still have to copy/paste it from your command line to be able to use it.
It would be very handy to immediately have the Guid available in your clipboard.

You can do this using the following powershell script :

[reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Clipboard]::SetText([System.Guid]::NewGuid().ToString())

This script will load the the Windows Forms assembly and get the Clipboard class to use the SetText method.  And … magic we have the Guid in our clipboard.

No comments:

Post a Comment