ValidatePattern Parameter Attribute

This topic contains 4 replies, has 3 voices, and was last updated by  marcoolinho Pappas 2 years, 2 months ago.

  • Author
    Posts
  • #27672

    marcoolinho Pappas
    Participant

    Hi.

    Would you be so kind and assist me?

    I want to specify two possible patterns for my parameter $ComputerName in my Advanced Script. How do I write two regex-s? How do I separate them and enclose them with quotes and brackets?

    Thank you very much for your help in advance.

  • #27673

    Rob Simmers
    Participant

    Not sure that ValidatePattern could be specified twice for one parameter or that you could have it check against multiple patterns. It would probably be better to have a single pattern match. What are the possible computer names? Do you have any regex patterns built?

  • #27675

    Dave Wyatt
    Moderator

    Regex has an "or" operator (the pipe symbol) that can be used to combine two patterns into a single regex. However, the ValidatePattern attribute produces error messages that are extremely unfriendly to users, and its use is generally discouraged. Using ValidateScript, you can get the same functionality, but also produce any error messages you like via the "throw" statement.

  • #27678

    Rob Simmers
    Participant

    @dave – Here is another option I'd seen before which uses a Regex comment to give a descriptive error message:

    http://powershell.com/cs/blogs/tips/archive/2013/07/19/using-validatepattern-attribute.aspx

  • #27911

    marcoolinho Pappas
    Participant

    Thank you everyone for your assistance. Please excuse my late response.
    I used the "|" pipe sign to combine two Regex-s because I needed it for my function which creates Gen2 VMs on my Hyper-V server and I wanted them to be according to my naming standards: for virtual servers i.e. "VM-Server-DC01" and for virtual workstations i.e. "W81Ent01".

    [ValidatePattern("^VM\-Server\-([A-Z]{2,3})([0-9]{1,2})$|^W81([A-Z]{3})([0-9]{1,2})$")]

    What do you think?

You must be logged in to reply to this topic.