Modifying the New-Guid Cmdlet

I’m deep in the weeds right now writing new content about my experience with Azure and Azure PowerShell. So, what a better time to have an idea, write a quick function, and then create its own post and publish it. Or, maybe not. It’s quick and easy and I think there are people for which this might be good. You can create a function that will run in place of a PowerShell cmdlet, in order to add additional features, take them away, or whatever other reason, or reasons, one might have. That said, and you may notice this momentarily, just because my function of the same name runs instead of the cmdlet, doesn’t mean there isn’t a way to run the original cmdlet.

As one might expect, GUIDs are used all over Azure for identification purposes. I’m running into them everywhere. I don’t want to publish the GUIDs associated with my Tenant, Subscription, etc., so I’ve been replacing mine with this: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. Well, since I use PowerShell to shave off all the seconds I can, I now have a function that will give me an X GUID–we’ll call it–if that’s what I want. We’ll start with an example of it being used, which will then be followed by the code to make that happen. If you’re curious why my New-Guid function runs in place of the cmdlet with the same name from the Microsoft.PowerShell.Utility PowerShell module, then read up on the PowerShell command precedence rules. This is what to remember about the order, however:

  1. Alias
  2. Function
  3. Cmdlet
  4. External executable files (programs and non-PowerShell scripts)
New-Guid

Guid
----
d6dde62e-46fc-4f37-b75a-c116f003a270
New-Guid -x

Guid
----
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

And, here’s the function that makes the above invocations a possibility. I’ll drop it in my profile script and then it’ll be available in my PowerShell session right when I need it, just like New-Guid already was.

function New-Guid {
    [CmdletBinding()]
    Param (
        [Parameter()]
        [switch]$x
    )

    if ($x)
    {
        [PSCustomObject]@{'Guid' = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}
    }
    else
    {
        Microsoft.PowerShell.Utility\New-Guid
    }
}

If you’re like me, perhaps you just had an idea. Allow it to accept any single character and create the GUID with the character. Okay, back to what I should be doing with this time.

Leave a Reply

Your email address will not be published. Required fields are marked *