45

I would like the second function call in this script to throw an error:

function Deploy
{

param(

    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$BuildName

    )
    Write-Host "Build name is: $BuildName"

}

Deploy "Build123"

Deploy #Currently prompts for input

Prompting is great for using the script interactively, but this will also be executed by our build server.

Is my best bet just doing some custom validation with an if or something?

Josh Earl
  • 18,151
  • 15
  • 62
  • 91
  • 13
    Note that if you run powershell.exe with the `-NonInteractive` flag, missing mandatory parameters will cause an error and result in a non-zero exit code for the process. – Emperor XLII May 21 '12 at 13:07
  • Check out this Q&A where I posted a solution that doesn't involve manually invoking the PowerShell executable, using background jobs instead. https://stackoverflow.com/questions/45935954/testing-for-mandatory-parameters-with-pester/62445526#62445526 –  Jun 18 '20 at 08:26

2 Answers2

60

Once the parameter is marked as mandatory PowerShell will prompt for value. That said, if you remove the mandatory attribute then you can set a default value with a throw statement:

function Deploy
{
    param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$BuildName=$(throw "BuildName is mandatory, please provide a value.")
    )

    Write-Host "Build name is: $BuildName"
}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • 1
    Strangely, for pipeline-bound parameters the default value is still evaluated which seems to make this technique unusable for throwing an error when a parameter is missing...at least if you're using pipeline parameters. – alx9r Feb 21 '15 at 00:58
  • 1
    [This question](https://stackoverflow.com/questions/33600279) discusses the unfortunate shortcomings of this workaround if you're using pipeline parameters. – alx9r Nov 09 '15 at 18:36
35

@Emperor XLII has a nice comment in the question that I think can be a better answer for some use cases:

if you run powershell.exe with the -NonInteractive flag, missing mandatory parameters will cause an error and result in a non-zero exit code for the process.

The reasons to use this can be:

  1. You have a lot of such Mandatory=$true parameters and the cost is high to convert all of them.
  2. The script will be used both interactively and non-interactively, and when run interactively you do want to be prompted for missing parameters.
Community
  • 1
  • 1
ohw
  • 1,619
  • 12
  • 20