1

I am new with powershell and I had been researching how to create custom objects.

With "New-Module" I always find results like "New-Module -AsCustomObject -ScriptBlock". Like this for example:

$myObject = New-Module -AsCustomObject -ScriptBlock {
    function myFunc(){
       return "myFunc";
    }
}

but when I try without "-ScriptBlock":

$myObject = New-Module -AsCustomObject {
 
    function myFunc(){
       return "myFunc";
    }
}

it appears to have the same effect to me. I get a custom object with a function myFunc in both cases.

Am I missing something? Or actually it will have no difference in this particular case?

mklement0
  • 382,024
  • 64
  • 607
  • 775
user1139359
  • 159
  • 1
  • 10

1 Answers1

2
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.

mklement0
  • 382,024
  • 64
  • 607
  • 775