Creating Custom Mandatory Parameters

by Jul 12, 2016

All Versions

While you can declare a parameter as mandatory, this leaves not much control to you. If the user omits the mandatory parameter, PowerShell prompts the user with its ugly default prompt.

Here is an alternative that allows you to define your very own prompt in case a user did not submit the parameter:

function Get-Name
{
  #Content
  param
  (
    $Name = $(
      Write-Host 'Please, enter your name: ' -ForegroundColor Yellow -NoNewLine
      Read-Host 
    )
  )
    
  "You entered: $Name"
}

When you call Get-Name and submit an argument, the function runs silently. If you do not specify your name, it asks for it and uses the colors and prompt text that you define.

 
PS> Get-Name -Name Test
You entered: Test

PS> Get-Name
Please enter your name: Tobias
You entered: Tobias
 

Twitter This Tip! ReTweet this Tip!