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?
To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out. Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.
By default, PowerShell parameters are optional. When a user does not submit arguments to a parameter, PowerShell uses its default value. If no default value exists, the parameter value is $null. This is not always desired. There are situations when default values simply do not make sense.
You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.
You can use a mandatory parameter to prompt user input in the PowerShell script or function during the execution. Here is an example of function Name that asks for the user input when it is run. Copy function Name { param( [Parameter(Mandatory)] [string]$name ) Write-Output "Your name is $name." }
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" }
@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:
Mandatory=$true
parameters and the cost is high to convert all of them.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With