简体   繁体   中英

Make all of the function's arguments mandatory by default

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM