locked
Invoke-Command returning data from multiple sessions. RRS feed

  • Question

  • Hi folks,

       I have a simple script that needs to connect to multiple machines, execute a command and return a status.  The issue I am having is matching the return results from each machine with its matching session (and machine name).

    $s = NewPSSession -ComputerName $hostNames
    $results = Invoke-Command -Session $s -ScriptBlock { param($p1) ... execute command... return $retVar } -ArgumentList $parm
    
    $s
    $results
    
    # $s  will list the sessions (id, name, computername)
    # $results  will list a value for each session, so for 4 machines I get something like:-
    #  0
    #  3
    #  4
    #  6
    

    What I need to do is correlate the ComputerName property and the result value into a table

    ComputerName   Value

       Bob                   0
       Fred                  3
       Dave                 4

    The $results value just seems to be an array, however, I can find no documentation around the order of the values stored in it.  Are they in order of when the result was returned by invoke-command, or are they in order of  the sessions in $s  (so if 'Fred' is the second array element in $s, then 3 would be the second element in $results).

    I need to execute the commands concurrently.   

    My thought at the moment is to return a tuple [hostname,status] from invoke command.

    Regards

    Monday, January 14, 2019 10:19 PM

Answers

  • $sb = {
        param ($p1)
        .. . execute command...
        [pscustomobject]@{Value = $retVar }
    }
    Invoke-Command -Session $s -ScriptBlock $sb -ArgumentList $parm |
         Select-Object PsComputerName, Value


    \_(ツ)_/


    • Marked as answer by AndyW2007 Monday, January 14, 2019 11:57 PM
    • Edited by jrv Tuesday, January 15, 2019 12:41 AM
    Monday, January 14, 2019 11:11 PM