Search code examples
arrayspowershellhashtable

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


I need to declare an array parameter in an called PS script. The array coming in from the caller/source script is in a hash table:

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

Call: Z:\called.ps1 $myHashTable

In 'called.ps1', what is the difference between

Param(
$myArr
)

,

Param(
[array] $myArr
)

and

Param(
[array[]] $myArr
)

?


Solution

  • You can test that fairly directly. [grin] your examples give ...

    • any type = remains that type
    • 1d array = converts to an array if not one already
    • 2d array = converts to a jagged array (array of arrays) if not one already

    demo code ...

    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'
    

    output ...

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