Using Custom Prompts for Mandatory Parameters

by Mar 15, 2019

When you define mandatory parameters in PowerShell, the user gets prompted for the value if it is missing. The prompt uses the parameter name only as you can see when you run this code:

param
(
  [Parameter(Mandatory)]
  [string]
  $UserName

)

"You entered $Username"
 
UserName: tobi
You entered tobi 
 

To get more descriptive prompts, you can use more explicit variable names:

param
(
  [Parameter(Mandatory)]
  [string]
  ${Please provide a user name}

)

$username = ${Please provide a user name}
"You entered $Username"
 
Please provide a user name: tobi
You entered tobi  
 

Simply wrap the param() structure in a function to produce commands:

function New-CorporateUser
{
    param
    (
      [Parameter(Mandatory)]
      [string]
      ${Please provide a user name}
    )

    $username = ${Please provide a user name}
    "You entered $Username"
}
 
PS C:\> New-CorporateUser
Cmdlet New-CorporateUser at command pipeline position 1
Supply values for the following parameters:
Please provide a user name: Tobi
You entered Tobi 
 

The flip side is that blanks and special characters in parameter names make it impossible to assign values via command line because parameters cannot be quoted:

 
PS C:\> New-CorporateUser -Please  provide a user name
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!