Reputation: 21990
TIL that all of the function's arguments are optional by default.
function f([int] $x) {
if (!$x) {
echo "Why so null?"
}
}
f
Et voilà! The forgotten $x
argument just became a $null
> .\script.ps1
Why so null?
For $x
to be mandatory, its declaration needs to be updated to [parameter(Mandatory=$true)][int] $x
, which doesn't appear to be a sane solution if there's more than one or two parameters. It'd be nice to have this behavior as the default, because otherwise a huge codebase containing a lots of functions looks a little bit verbose and oversaturated with attributes.
At first glance, Set-StrictMode
sounds like a magic word that should make all of the function's arguments mandatory by default, but unfortunately it doesn't behave this way.
What are the best practices for making all of the function's arguments in the scope mandatory?
Upvotes: 4
Views: 346
Reputation: 1562
The best practice is to mark all mandatory arguments as mandatory.
With PowerShell all mandatory arguments must be explicitly specified or else they will be considered optional, at this time no catch all exists.
You can find more on PowerShell argument properties here.
Upvotes: 1