简体   繁体   中英

Invoke-Command - use predefined function and object

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.

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; eg, ... -ArgumentList $object, 'foo'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM