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"
}