PowerShell:区别 [array] 与 [array[]]

PowerShell: Difference [array] vs [array[]]

我需要在调用的 PS 脚本中声明一个数组参数。来自 caller/source 脚本的数组位于散列 table:

$Array = @(1, 2, 3)
$myHashTable = @{myArr = $Array}

致电: Z:\called.ps1 $myHashTable

与'called.ps1'有什么区别

Param(
$myArr
)

,

Param(
[array] $myArr
)

Param(
[array[]] $myArr
)

?

您可以相当直接地测试它。 [grin]你的例子给...

  • 任何类型 = 仍然是那个类型
  • 1d 数组 = 转换为数组(如果还没有的话)
  • 2d 数组 = 转换为锯齿状数组(数组的数组)如果还没有的话

演示代码...

function Test-Parameter
    {
    Param
        (
        $GenericVar,
        [array]$OneD_Array,
        [array[]]$TwoD_Array
        )

    $GenericVar.GetType()
    $OneD_Array.GetType()
    $TwoD_Array.GetType()
    }

Test-Parameter -GenericVar 'One' -OneD_Array 'Two' -TwoD_Array 'Three'

输出...

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
True     True     Object[]                                 System.Array
True     True     Array[]                                  System.Array