Getting a return code from invoke-command

This topic contains 4 replies, has 2 voices, and was last updated by  marius 2 months ago.

  • Author
    Posts
  • #71312

    marius
    Participant

    I need to get a return code from invoke-command based on the actions performed indice the scriptblock.
    What is the right syntax to set a return code (inside the scriptblock) and to get it in the script using invoke-command?
    Regards
    marius

  • #71315

    Sam Boutros
    Participant

    You can get data back from remote command execution via a simple variable assignment as in:

    $Result = Invoke-Command -ComputerName myComputer -ScriptBlock { Get-Service }
    $Result
    

    Whatever the scriptblock dumps in the standard pipeline you'll get in the $Result variable (as a deserialized object)

    • #71321

      marius
      Participant

      Many thanks for the solution you suggested.
      I'll try as soon as possible.
      However, my problem is a little bit more complex, and my code should look like the following (fictional) sample:

       
      $Result = Invoke-Command -ComputerName myComputer -ScriptBlock { 
          ...
          ...
      if ($a > $b)
          {
          $result = 1
          }
          ...
          ...
          ...
      if ($c > $d)
          {
          $result = 2
          }
          ...
          ...
          }
      $Result
      

      How can I make the scriptblok return 1 or 2 ot anything else based on the contents of the scriptblock?
      Regards
      Marius

    • #71356

      Sam Boutros
      Participant

      You need to put the information that you wish to receive back from the scriptblock in the pipeline as in:

      $Result = Invoke-Command -ComputerName myComputer -ScriptBlock { 
          ...
          ...
      if ($a > $b)
          {
          $returncode = 1
          }
          ...
          ...
          ...
      if ($c > $d)
          {
          $returncode = 2
          }
          ...
          ...
      $returncode
      }
      $Result
      
  • #72685

    marius
    Participant

    Many thanks!
    marius

You must be logged in to reply to this topic.