Interactive PowerShell sessions prompt the user when a required parameter is omitted. Shay Levy offers a workaround to this problem. The problem is that workaround does not work when you use the pipeline to bind parameters.
Consider this example:
function f {
[CmdletBinding()]
param
(
[Parameter(ValueFromPipeLineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]$a=$(throw "a is mandatory, please provide a value.")
)
process{}
}
$o = New-Object psobject -Property @{a=1}
$o | f
This throws an exception despite that $o.a
is a perfectly good value to bind to f -a
. For some reason PowerShell evaluates the default value for parameter $a
even if there is a value for $a
that is destined to be bound from the pipeline.
Is there some other way to force PowerShell to throw an exception when a mandatory parameter is missing when running interactively?
Why does this matter? It wastes programmer time. Here's how:
It's pretty normal for the stack trace to be 20 calls deep. When a call deep in the call stack blocks because it didn't receive a mandatory parameter things become very inefficient to debug. There is no stack trace, no error messages, and no context. All you see is a prompt for the parameter value. Good luck guessing exactly why that occurred. You can always debug your way to a solution, it just takes way more time than it should because you're not getting the information you normally would from a thrown exception.
Suppose you are running a series of configuration test cases and one of 1000 has this problem. On average, 500 of those test cases don't run. So you only get test results from half of your cases on this test run. If those test runs were running overnight, you might have to wait another 24 hours to get the results. So now you're iterating slower.