"New-Module -AsCustomObject" 中“-Scr​​iptBlock”的作用是什么

What is the effect of "-ScriptBlock" in "New-Module -AsCustomObject"

我是 powershell 的新手,我一直在研究如何创建自定义对象。

使用“New-Module”时,我总能找到类似“New-Module -AsCustomObject -ScriptBlock”的结果。 例如:

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

但是当我尝试不使用“-Scr​​iptBlock”时:

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

它似乎对我有同样的效果。在这两种情况下,我都得到了一个带有函数 myFunc 的自定义对象。

我错过了什么吗?或者实际上它在这种特殊情况下没有区别?

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

script block { ... } 作为 命名的 参数 传递给 -ScriptBlock 参数。即目标参数显式命名.

PowerShell 命令可选择支持 positional arguments,其中目标参数为 not 命名,而不是所有未命名参数中的相对位置暗示目标参数。

New-Module cmdlet 的第一个位置参数确实是-ScriptBlock,也就是说
-ScriptBlock{ ... }块之前可以省略这里,这就是为什么你的两个命令是等价:

# Same as above, except that -ScriptBlock is *implied*, positionally.
New-Module -AsCustomObject { function myFunc(){ return "myFunc"; } }

(注意-AsCustomObjectswitch参数(flag)根据定义named,所以对位置参数绑定。)


您可以通过查看其 syntax diagrams 来了解给定命令的哪些参数是位置参数,您可以使用 New-Module -? 或 [=21] 获得=]:

# 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>]

参数 name 周围的 [...] 告诉您给定参数接受 positional 参数,在这种情况下仅适用于 -ScriptBlock,因此它是该参数集中的第一个也是唯一一个位置参数。


了解更多关于:

  • 如何阅读语法图,包括以编程方式列出命令位置参数的辅助函数,请参阅

  • 在编写函数和脚本时声明您自己的位置参数,请参阅this answer