Better Prompting for Mandatory Parameters

by Apr 28, 2016

When you do not submit an argument to a mandatory parameter, PowerShell prompts you for a value. You don’t have much control over how this is done, and most find it ugly.

To use your own prompting, make the parameter optional, and provide code that is executed to define the default value. When no argument is submitted, PowerShell tries to retrieve the default value, and executes your own prompting logic.

Take a look at what this looks like. With the upcoming example, you get a new function called Get-Birthday that is fully automatable, so you can submit arguments. If you don’t, you get a pretty nice prompt:

 
PS> Get-Birthday  -Date 1/1/2000
You are born on a  Saturday!
 
PS> Get-Birthday 
Enter your birthday [>>>] no!
Should be a date. Try  again! 
Enter your birthday [>>>] ok
Should be a date. Try  again! 
Enter your birthday [>>>] 1/1/2000
You are born on a Saturday!

We are going to re-use the Get-UserInput function from the previous tip to create the actual custom prompt.:

function Get-UserInput
{
  param
  (
    [Parameter(Mandatory=$true)]
    $Prompt,
    [ScriptBlock]
    $Validator = $null,
    $ErrorMessage = 'Incorrect. Try again!'
  )

  do
  {
    Write-Host "$Prompt " -NoNewline
    Write-Host "[>>>] " -ForegroundColor Yellow -NoNewline
    $userinput = Read-Host

    if ($Validator -ne $null)
    {
      $_ = $userinput
      $ok = & $Validator 
    }
    else
    {
      $ok = $true
    }

    if (!$ok)
    {
      Write-Host $ErrorMessage -ForegroundColor Red
    }
  } until ($ok)

  $userinput
}

function Get-Birthday
{
  param
  (
    [DateTime]
    $Date = (Get-UserInput -Prompt 'Enter your birthday' -Validator { $_ -as [DateTime] } -ErrorMessage 'Should be a date. Try again!')
  )

  $realDate = Get-Date -Date $Date
  $weekday = $realDate.DayOfWeek
  "You are born on a $weekday!"
}

Twitter This Tip! ReTweet this Tip!