将哈希表和参数作为参数传递给 powershell invoke-command

Passing hashtable and args to powershell invoke-command as arguments

通常可以做到以下几点:

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

并显式传递参数或像这样通过 splatting 传递参数:

$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

我想在使用 invoke 命令时以某种方式复制该语法的行为。 理想情况下是这样的语法:

$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'}

我看过这个回答: 建议将脚本块包装起来,以便散列哈希表

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

我不确定如何处理 $args 和明确指定的参数(例如 Parameter2)。

没有什么能阻止您解构、修改然后代理 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
}