New-Module -AsCustomObject -ScriptBlock { function myFunc(){ return "myFunc"; } }
passes the script block { ... }
as a named argument to the -ScriptBlock
parameter. That is, the target parameter is explicitly named.
PowerShell commands can choose to alternatively support positional arguments, where the target parameter is not named, and instead the relative position among all unnamed arguments implies the target parameter.
The New-Module
cmdlet's first positional parameter is indeed -ScriptBlock
, which means that
-ScriptBlock
before the { ... }
block can be omitted here, which is why your two commands are equivalent:
# Same as above, except that -ScriptBlock is *implied*, positionally.
New-Module -AsCustomObject { function myFunc(){ return "myFunc"; } }
(Note that the -AsCustomObject
switch parameter (flag) is by definition named, so it has no impact on positional parameter binding.)
You can learn which of a given command's parameters are positional by looking at its syntax diagrams, which you can obtain with New-Module -?
or Get-Command New-Module -Syntax
:
# Note: PowerShell commands can have multiple *parameter sets*, with
# distinct parameter combinations.
# Here, I've omitted the 2nd parameter set that doesn't apply to
# your call, because it doesn't use the -Name parameter.
PS> Get-Command -Syntax New-Module
New-Module [-ScriptBlock] <scriptblock> [-Function <string[]>] [-Cmdlet <string[]>] [-ReturnResult] [-AsCustomObject] [-ArgumentList <Object[]>] [<CommonParameters>]
The [...]
around a parameter name tells you that a given parameter accepts a positional argument, and in the case at hand that only applies to -ScriptBlock
, so it is the first and only positional parameter in that parameter set.
To learn more about:
how to read syntax diagrams, including a helper function that programmatically lists a command's positional parameters, see this answer
declaring your own positional parameters when authoring functions and scripts, see this answer.