PowerShell Tip: Creating GUIDs and Code Generation

By Michael Flanakin @ 11:30 AM :: 4916 Views :: Development, PowerShell :: Digg it!

PowerShell

I should start off by saying this isn't really about hard-core code generation. It's more about simplifying some of the more repetitive tasks we tend to do during development. In this instance, I needed to get 7 GUIDs to use in some test code. Sure, I could've use the Create GUID tool in Visual Studio, but what fun is that? Besides, I hate manual tasks and this tool would have forced me down a ~24 step process. No thanks. I'll stick to the 3 steps PowerShell can give me.

First thing's first, how do we create a GUID in PowerShell? I'm going to fall back to .NET for this one.

[Guid]::NewGuid()

If you run this, you'll get a blank line. What's up with that!? Admittedly, I'm not 100% sure why this is happening, but I have a pretty good guess. GUIDs are surrounded by curly-braces ({}), which are interpreted by PowerShell to be a script block. Putting 2 and 2 together, I'm assuming PowerShell thinks this is a script to run. Easy fix.

[Guid]::NewGuid().ToString()

That's it. The only other thing I had to do was add in my other formatting to create the GUID in code and slap that in a loop.

foreach ($i in 1..7) { 'new Guid("{0}")' -f [Guid]::NewGuid() }

You'll notice I opted to use the PowerShell shortcut syntax for string formatting. If you missed it, I talked about it as well as the static-method-calling syntax last week.

This tiny exercise reminded me of a pretty advanced Excel spreadsheet I created years ago because I was sick of typing the same bit of code over and over again. Since then, other tools, like GhostDoc and Resharper, have augmented my developer experience, enabling a much higher level of productivity than I had back then. Nonetheless, there is still room for improvement. This makes me wonder how much PowerShell could do for me with respect to code generation.

Ratings