Tobias Pahlke
Tobias Pahlke

Reputation: 11

Powershell parameter validation without throwing exception

I have a Powershell script like this

    Param(
   [Parameter(Mandatory=$True,Position=1)]
   [string]$variable1,

   [Parameter(Mandatory=$True,Position=2)]
   [string]$variable2,

   [Parameter(Mandatory=$True,Position=3)]
   [int]variable3
   )... something happens then

Now I want to check before going on with the script if variable 1 for example is A, B or C variable2 is D,E or F and variable3 is 1,4,5

is there any possibility to check the Parameters right after Input? So that if variable1 Errors you have to redo it but if variable2 has a error you just have to redo variable2 and not variable1 as well?

Upvotes: 1

Views: 784

Answers (2)

Hashman
Hashman

Reputation: 141

function testFunc{
    Param(
    [Parameter(Mandatory=$True,Position=1)]
    $variable1,

    [Parameter(Mandatory=$True,Position=2)]
    $variable2,

    [Parameter(Mandatory=$True,Position=3)]
    $variable3)

    $acceptable1 = @("A", "B", "C")
    $acceptable2 = @("D", "E")
    $acceptable3 = @(1, 2, 3)

    while((-Not($acceptable1.Contains($variable1))) -or (-Not($acceptable2.Contains($variable2))) -or (-Not($acceptable3.Contains($variable3)))){
        if (-Not($acceptable1.Contains($variable1))){
            $variable1 = Read-Host "Please re-enter Variable1"
        }
        if (-Not($acceptable2.Contains($variable2))){
            $variable2 = Read-Host "Please re-enter Variable2"
        }
        if (-Not($acceptable3.Contains($variable3))){
            $variable3 = Read-Host "Please re-enter Variable3" 
            if([int]$variable3 -eq [double]$variable3){
                $variable3 = [int] $variable3
            }
        }
    }
}

Not the most elegant, but it works.

I defined 3 sets of acceptable inputs then checked against the set. It will continue to loop until each of the inputs is correct. Due to Read-Host taking in Strings, I checked to see if the int cast would be equal to the double cast, then set the variable to be that int.

This will only prompt for incorrect inputs to be corrected as you specified.

Upvotes: 0

bouvierr
bouvierr

Reputation: 3791

Specify the acceptable values by using the ValidateSet attribute.

From help documentation about_Functions_Advanced_Parameters:

ValidateSet Attribute
    The ValidateSet attribute specifies a set of valid values for a 
    parameter or variable. Windows PowerShell generates an error if a
    parameter or variable value does not match a value in the set. In
    the following example, the value of the Detail parameter can only
    be "Low," "Average," or "High."

   Param
      (
        [parameter(Mandatory=$true)]
        [ValidateSet("Low", "Average", "High")]
        [String[]]
        $Detail
      ) 

Upvotes: 1

Related Questions