Using regular and Validateset validation parameter legality in PowerShell _powershell

Source: Internet
Author: User

Apply to PowerShell 2.0 or later

When you use PowerShell to create a function, make sure you tell PowerShell what kind of value your parameters expect. For example you want users to enter the week

Copy Code code as follows:

function Get-weekday
{
Param
(
$Weekday
)

"You chose $Weekday"
}

At this point, the user can enter any value, even if the value is not a legitimate week, such as week Seven
Copy Code code as follows:

Ps> Get-weekday-weekday Noweekday
You chose Noweekday

Maybe you've seen it before. How the regular expression type is validated:

Copy Code code as follows:

function Get-weekday
{
Param
(
[Validatepattern (' monday| tuesday| wednesday| thursday| friday| saturday| Sunday ')]
$Weekday
)

"You chose $Weekday"
}

Now, once the user enters a string that does not match the pattern you specified, PowerShell throws an exception, but the exception message is not friendly enough. When you output parameters, the console or the ISE editor is not smart to prompt:

So the better way should be to use Validateset:

Copy Code code as follows:

function Get-weekday
{
Param
(
[Validateset (' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday ', ' Sunday ')]
$Weekday
)

"You chose $Weekday"
}

The user is now limited to the set of values you specify in the output parameter, and the ISE also intelligently prompts the user to allow a list of values. If you could be in. NET, it's easier to find an enumeration value that just describes the parameters you need:
Copy Code code as follows:

function Get-weekday
{
Param
(
[System.dayofweek]
$Weekday
)

"You chose $Weekday"
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.