Search code examples
powershellparameter-passingparameter-splatting

Can I use splatting to pass arguments to a non-powershell executable?


Can I do something like this?

$splatting_table = @{
   "-parameter" = "value"
   "-parameter2" = "value2"
}
.\external-command.exe @splatting_table

as an equivalent for

.\external-command.exe -parameter value -parameter2 value2

Solution

  • While it is technically possible to use a hashtable for splatting with external programs, it will rarely work as intended.[1]

    Instead, use an array:

    $splatting_array = 
       '-parameter', 'value',
       '-parameter2', 'value2'
    
    .\external-command.exe @splatting_array
    

    Note:

    • $splatting_array is simply a flat array[2] - formatted for readability in element pairs that reflect option names and their values on a single line each - whose elements PowerShell passes as individual arguments to an external program.

    • When calling external programs, explicit splatting of arrays via sigil @ isn't even strictly necessary, so passing $splatting_array as-is above works too.


    [1] With hashtable-based splatting, do not include the - sigil in the key names (e.g., use parameter, not
    -parameter); aside from that, PowerShell will join your entries with a : when constructing the command line for the external program, which few programs support; e.g., hash-table entry parameter = 'value' translates to
    -parameter:value.

    [2] You may enclose the array elements in @(...), the array-subexpression operator if you want to make it more obvious that an array literal is being defined, but it isn't strictly necessary.