Prompt Validator PowerShell Function

Another potentially useful function if you have lots of prompts in your PowerShell script/program.

Usage Examples:

$Answer = PromptValidator
$Answer = PromptValidator -YesOrNo
$Answer = PromptValidator "Bananas"
$Answer = PromptValidator "Bananas","Apples","Pears" -CaseSensitive
$Answer = PromptValidator "NotDefault1","NotDefault2" -AllowCR

In the last example, carriage return would give you the default option say.

The Code:

FUNCTION PromptValidator{
   Param([System.Object]$In,[Switch]$YesOrNo,[Switch]$CaseSensitive,[Switch]$AllowCR)
   [System.Array]$Answers = $In
   WHILE ($true){
      $ReadIn = Read-Host
      IF($YesOrNo){ IF( ($ReadIn -eq "YES") -or ($ReadIn -eq "Y") ){ RETURN $TRUE  } }
      IF($YesOrNo){ IF( ($ReadIn -eq "NO")  -or ($ReadIn -eq "N") ){ RETURN $FALSE } }
      IF($Answers -and  $CaseSensitive){ FOREACH ($a in $Answers){ IF($ReadIn -ceq $a){ RETURN $ReadIn } } }
      IF($Answers -and !$CaseSensitive){ FOREACH ($a in $Answers){ IF($ReadIn -eq  $a){ RETURN $ReadIn } } }
      IF(!$YesOrNo -and !$Answers -and ($ReadIn.length -gt 0) ){ RETURN $ReadIn }
      IF(!$YesOrNo -and $AllowCR  -and ($ReadIn.length -eq 0) ){ RETURN $NULL }
   }
}

Comments