powershell

How to in-place expand an array in PowerShell?


When add an array (A) in an array (B), the PowerShell will treat A itself as an element of B.

Is it possible to in-place expand A, so that all elements of A will be elements of B?

$SNs = "0x66", "0x88"

$splat = @(
    'abc',   
    '--serial-number', $SNs,  # How to in-place expand $SNs
    '--sign'
)

Write-Host "Splat Count = " $splat.Count  # will be 4, Expected to be 5


Solution

  • You need $SNs in a new line or use semicolon as delimiters instead:

    $SNs = '0x66', '0x88'
    $splat = @(
        'abc'
        '--serial-number'; $SNs
        '--sign'
    )
    $splat.Count
    
    # Or:
    $splat = @(
        'abc'
        '--serial-number'
        $SNs
        '--sign'
    )
    $splat.Count
    

    Everything inside the Array subexpression operator @( ) is enumerated to construct a new array and the commas are preventing that enumeration from happening.