Search code examples
powershellscriptblock

Executing multiple commands in a scriptblock and returning multiple responses


I'd like to connect to a remote host, run 2 commands and return the seperate responses. However I'd like to do this as part of one scriptblock. I've done this before with one command but no joy with two. For example having

gc "C:\test.txt"

and

get-webservice | ? {$_.Name -eq "foo"}

combined into a scriptblock and passing that scriptblock to Invoke-Command and extracting the individual responses from that call.


Solution

  • One option is to load your results into a hash table, the return that.

    $Scriptblock = 
    {
      $response = @{}
      $response.dir = gc "C:\test.txt"
      $response.service = get-webservice | ? {$_.Name -eq "w32time"}
      $response
    }
    
    $result = &$Scriptblock
    

    This eliminates any ambiguity in the results of any of the commands returns a null.