Mandatory Parameters with a Dialog

by Feb 6, 2015

All Versions

Typically, when you declare a parameter as mandatory, and the user does not submit it, PowerShell takes care and prompts the user for the value:

function Get-Something
{
  param
  (
    [Parameter(Mandatory = $true)]
    $Path 
  )

  "You entered $Path."
}

The result looks like this (you do not have much control over how the user is prompted):

 
PS> Get-Something -Path test
You entered test.

PS> Get-Something 
Cmdlet Get-Something at command pipeline position 1
Supply values for the following parameters:
Path: test
You entered test.

PS>  
 

But did you know that you can get a mandatory parameter this way, too?

function Get-Something
{
  param
  (
    $Path = $(Read-Host 'Please, enter a Path value')
  )

  "You entered $Path."
} 

This approach gives the control to you, and this is what it looks like:

 
PS> Get-Something -Path test
You entered test.

PS> Get-Something 
Please, enter a Path value: test
You entered test.

PS>  
 

Twitter This Tip! ReTweet this Tip!