4

#PSTip How to properly validate GUID parameter

Most of you probably know how to create a Globally Unique Identifier (GUID) with the following code:

[System.Guid]::NewGuid()

But, let’s say, I have a function that has a GUID parameter. To validate the given GUID as an input, I’d use a regular expression with the ValidatePattern attribute.

Function Test-Foo {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory,ValueFromPipeline)]
        [ValidatePattern('(\{|\()?[A-Za-z0-9]{4}([A-Za-z0-9]{4}\-?){4}[A-Za-z0-9]{12}(\}|\()?')]
        [string[]]$GUID
    )

    Begin{}

    Process{
        $_
    }

    End{}
}

The regular expression works great but doesn’t fully cover all the existing GUID formats. The ValidateScript attribute combined with the Parse method of the System.Guid object will help improve the validation.

Let’s see this in action:

Function Test-Bar {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory,ValueFromPipeline)]
        [ValidateScript({
            try {
                [System.Guid]::Parse($_) | Out-Null
                $true
            } catch {
                $false
            }
        })]
        [string[]]$GUID
    )

    Begin{}

    Process{
        $_
    }

    End{}
}

I’ll first create an array of 5 random GUIDs with different formats. The surrounding parenthesis display the content while assigning the output to a variable.

($ar = "N","D","B","P","X" | ForEach {
      [System.Guid]::NewGuid().ToString($_)
})

1Let’s pass this array of 5 valid GUIDs to the first function that uses the regular expression:

2The error above is expected as the regular expression doesn’t cover the 5th format. There is a second issue with the regular expression–it would report an invalid GUID that mixes 2 or 3 different formats as valid.

3The Test-Foo function validates the above GUID although it isn’t valid.

Now, let’s try the second function that uses the validation script and parse method:

4No error, all GUIDs are valid. The validation script method fixes the second issue as well:

5

Filed in: Columns, Tips and Tricks Tags: ,

One Pingback/Trackback

4 Responses to "#PSTip How to properly validate GUID parameter"

  1. nohandle says:

    Neat, when I saw the GUID approach I told to myself: Somebody else already did the hard work for you, why you don’t just use the Parse? And then you did and taught me there are more flavors of GUID, thanks.

  2. Derp McDerp says:

    Why didn’t you just make the parameter [guid[]] instead of [string[]] with some complicated validation code?

    • _Emin_ says:

      Very good question.

      My point was to compare a regex approach and a
      parse method approach. I took the parameter validation in a function to
      expose the difference and show the advantages of the parse method over
      the regex approach.

      That said, you’re absolutely right. For parameter validation, you
      can indeed define the parameter as a [GUID[]] array. It’s simple and
      works great.

      PowerShell is then doing some magic typeconversion behind the scene when you pass an array of strings.

      In this case the conversion being operated is actually using the Parse method because the system.guid has this method.

      Let’s consider:
      Function test-GUID {
      [CmdletBinding()]
      Param(
      [Parameter(Mandatory,
      ValueFromPipeline)][GUID[]]$GUID

      )
      Begin{}
      Process{
      $_
      }
      End{}
      }

      If you do:
      Trace-Command -Name TypeConversion -Expression { $ar | test-GUID } -PSHost

      You should see:
      DEBUG: TypeConversion Information: 0 : Converting “b5bb4e7cc90f415fbef63409292d2aa4″ to “System.Guid[]”.

      DEBUG: TypeConversion Information: 0 : Value to convert is scalar
      DEBUG: TypeConversion Information: 0 : Converting “b5bb4e7cc90f415fbef63409292d2aa4″ to “System.Guid”.
      DEBUG: TypeConversion Information: 0 : Parse result: “b5bb4e7c-c90f-415f-bef6-3409292d2aa4″.

      To understand the type conversion, I’ve used the following article
      http://blogs.msdn.com/b/powershell/archive/2013/06/11/understanding-powershell-s-type-conversion-magic.aspx

Leave a Reply

Submit Comment

© 9747 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: