0

Normally one can do the following:

function example{
     param(
         $Parameter1,
         $Parameter2
     )
     "Parameter1: $Parameter1"
     "Parameter2: $Parameter2"
     $PSBoundParameters
     $args
 }

and pass parameters explicitly or by splatting like so:

$options = @{parameter1='bounded parameter'}
example @options -Parameter2 'will be bounded too' 'this will go into args' -Parameter3 'this will too','and this one also'
Parameter1: bounded parameter
Parameter2: will be bounded too

Key        Value
---        -----
Parameter1 bounded parameters
Parameter2 will be bounded too
this will go into args
-Parameter3
this will too
and this one also

I would like to replicate that syntax's behavior somehow when using invoke command. Ideally somethings like this syntax:

$options = @{parameter1='bounded parameter';parameter3='this will too'}
Invoke-Command -Computername REMOTESERVER -ArgumentList @options 'will be bounded to parameter2' 'this will go into args', 'and this one also' -ScriptBlock {'block'}

I have seen this answer: https://stackoverflow.com/a/36283506/12603110 suggesting to wrap the script block with which allows splatting of hashtables

{param($Options)& <# Original script block (including {} braces)#> @options }

I'm unsure how to deal with the $args and explicitly specified parameters(e.g. Parameter2).

Yorai Levi
  • 473
  • 5
  • 17

1 Answers1

1

Nothing stops you from deconstructing, modifying and then proxying the arguments received by Invoke-Command:

$options = @{parameter1='bounded parameter'}

Invoke-Command -ArgumentList $options, "some other param", "unbound stuff" -ScriptBlock {
  # extract splatting table from original args list
  $splat,$args = $args

  & {
    param($Parameter1, $Parameter2)

    "Parameter1: $Parameter1"
    "Parameter2: $Parameter2"
    $PSBoundParameters
    $args
  } @splat @args
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206