30 October 2013

How do I – Validate user input is numeric from Powershell?


As the level of complexity and power of our Powershell scripts increase, it is inevitable that we reach a point where we need to interact with the user and prompt them for some information. In this case we were building a script to automate the creation and scaling of Search so we needed to know how many servers would be configured as Crawl servers. We all know the Read-Host cmdlet can provide us with the input, but how do we know that the user actually entered numeric only data? The easiest way is to simply use a try/catch block and attempt to convert the input to an int value. Here’s how we do that:

$numberOfCrawl = 0
$inputOK = $false
do
{
  try
  {
    [int]$numberOfCrawl = Read-Host -ForegroundColor red "Please enter the number of servers you wish to configure as Crawl servers."
    $inputOK = $true
  }
  catch
  {
    Write-Host -ForegroundColor red "INVALID INPUT!  Please enter a numeric value."
  } 
}
until ($inputOK)
Write-Host –ForegroundColor green "You chose to configure [$numberOfCrawl] Crawl servers."



We start by defining the $inputOK variable as false and then wrap the entire piece of code in a do/until loop that repeats until the user enters a valid numeric only value. Inside of this loop, we have a try/catch block. Inside the try, we attempt to assign the entered value from Read-Host to the $numberofCrawl variable which we cast as an int. If the user enters a non-numeric value, the cast will fail and will be caught by the catch. In the catch we output an error message in red text and simply allow the loop to restart from the top. If however, the user entered a valid numeric value, the cast will succeed afterwich we set the $inputOK variable to true thus allowing the loop to end gracefully. As a final step, we display the entered value to the user.



Cheers
C

No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...