0

I have the following code that will check to see if a user's input is an integer, but how could i extend it to make sure it is within the range from 1 through 4?

    $a = 0
$inputOK = $false
do
{
  try
  {
    $a = Read-Host "Please enter the number between 1 and 4"
    if (([int]$a) -and (1..4 -contains $a)) {
    $inputOK = $true}
  }
  catch
  {
    Write-Host -ForegroundColor red "INVALID INPUT!  Please enter a numeric value."
  } 

}
until ($inputOK)
Write-Host –ForegroundColor green "You have entered $a"

2 Answers 2

2

You can use a range and the -contains operator:

1..4 -contains $a

Or you can do it with 2 conditionals:

($a -ge 1) -and ($a -le 4)

-ge is "greater than or equal to" and -le is "less than or equal to"

Sign up to request clarification or add additional context in comments.

3 Comments

I was using the if statements, but couldn't get them to work within the try statement. Do I need another set of try/catch for that validation as well?
Edit your question to include the code you were trying. I don't see any if statements in your posted code. try/catch is not needed for this.
ok I put in your sugggestion and it works, kind of. It will check and if a letter is entered, it will say invalid input, but if the number is outside the range, it will just ask to reenter a number between 1 through 4, which is fine as it sends the message that it's still waiting for the num in the range
2

If you are writing functions, instead of writing custom blocks to validate your input, you can use the built in parameter validation. Here's a technet article that describes in in detail. In the ISE you can hit Ctrl+J and select advanced-function complete to auto create an example. Here's a simplified version.

function Test-ParameterValidation
{
[OutputType([String])]
Param
(
    # Param1 help description
    [Parameter(Mandatory=$true, 
               ValueFromPipeline=$true)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [ValidateCount(1,5)]
        [ValidateSet("sun", "moon", "earth")]
        [Alias("p1")] 
        $Param1,

        [AllowNull()]
        [AllowEmptyCollection()]
        [AllowEmptyString()]
        [ValidateScript({$true})]
        [ValidateRange(0,5)]
        [int]
        $Param2,

        [ValidatePattern("^\d{5}(?:[-\s]\d{4})?$")]
        [ValidateLength(5,10)]
        [String]
        $Param3
    )
    process{
    "p1 is $Param1"
    "p2 is $Param2"
    "p3 is $Param3"

    }
}

And sample inputs/outputs.

C:\ > Test-ParameterValidation -Param1 earth,moon
p1 is earth moon
p2 is 0
p3 is 

C:\ > Test-ParameterValidation -Param1 earth,moon,moon,moon,moon,moon
Test-ParameterValidation : Cannot validate argument on parameter 'Param1'. The number of supplied arguments (6) exceeds the maximum number of allowed arguments (5). Specify less than 5 arguments and then try the command again.
At line:1 char:34
+ Test-ParameterValidation -Param1 earth,moon,moon,moon,moon,moon
+                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-ParameterValidation], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-ParameterValidation


C:\ > Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 5 -Param3 ABC
Test-ParameterValidation : Cannot validate argument on parameter 'Param3'. The number of characters (3) in the argument is too small. Specify an argument whose length is greater than or equal to "5" and then try the command again.
At line:1 char:73
+ Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 5 -Param3 ABC
+                                                                         ~~~
    + CategoryInfo          : InvalidData: (:) [Test-ParameterValidation], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-ParameterValidation


C:\ > Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 5 -Param3 ABCDEF
Test-ParameterValidation : Cannot validate argument on parameter 'Param3'. The argument "ABCDEF" does not match the "^\d{5}(?:[-\s]\d{4})?$" pattern. Supply an argument that matches "^\d{5}(?:[-\s]\d{4})?$" and try the command again.
At line:1 char:73
+ Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 5 -Param3 ABCDEF
+                                                                         ~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-ParameterValidation], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-ParameterValidation


C:\ > Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 5 -Param3 11111-1111
p1 is earth moon moon moon
p2 is 5
p3 is 11111-1111

C:\ > Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 6
Test-ParameterValidation : Cannot validate argument on parameter 'Param2'. The 6 argument is greater than the maximum allowed range of 5. Supply an argument that is less than or equal to 5 and then try the command again.
At line:1 char:63
+ Test-ParameterValidation -Param1 earth,moon,moon,moon -Param2 6
+                                                               ~
    + CategoryInfo          : InvalidData: (:) [Test-ParameterValidation], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-ParameterValidation

These give you the ability to present validation errors in a standard "powershelly" way without having to write anything extra. Although you can use the ValidateScript() attribute if you need some heavy duty validation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.