Home > OS >  Invoke-Command - use predefined function and object
Invoke-Command - use predefined function and object

Time:07-05

i want to use a predefined function on a remote server with ps invoke and i need to send an object as parameter. This code always writes objects first element.

$object = @('a','b','c')

function testA {

    [CmdletBinding()]
    param (
        [Parameter()]
        [System.Object]
        $test
    )

    write-host $test
    
}

Invoke-Command -Session $session -ScriptBlock ${function:testA} -ArgumentList $object

Is there a way to pass function and object to the remote server with Invoke-Command?

Thx.

CodePudding user response:

If you want to pass the array stored in $object as a single argument and it is the only argument to pass, you need to wrap it in a transient single-element wrapper array when you pass it to -ArgumentList - otherwise, the array elements are passed as individual arguments:

# Alias -Args for -ArgumentList is used for brevity.
Invoke-Command -Session $session -ScriptBlock ${function:testA} -Args (, $object)

, $object uses the unary form of ,, the array constructor operator, to construct a single-element array whose only element is the $object array. -ArgumentList (-Args) then enumerates the elements of this transient array to form the individual arguments, and therefore passes the one and only element - which is the $object array - as-is.

Note that the problem only arises because you want to pass only a single argument; with two or more arguments, use of the binary form of , is needed anyway, which unambiguously makes $object as a whole its own argument; e.g., ... -ArgumentList $object, 'foo'

  • Related