Use Mandatory Parameters

by Apr 27, 2016

Mandatory parameters are cool: you can submit values to them for automated solutions, and you can omit them and get prompted interactively.

Here is an example:

function Get-Birthday
{
  param
  (
    [DateTime]
    [Parameter(Mandatory=$true)]
    $Date
  )

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

When you run Get-Birthday without arguments, PowerShell prompts you. Since the parameter expected a DateTime type, you even get re-prompted if your input does not match that type:

 
PS> Get-Birthday
cmdlet Get-Birthday at command pipeline position 1
Supply values for the following parameters:
Date: oh
Cannot recognize "oh" as a System.DateTime due to a format  error.
Date: ups
Cannot recognize "ups" as a System.DateTime due to a format  error.
Date: 1/1/2000
You are born on a Saturday! 
 

Twitter This Tip! ReTweet this Tip!