Author Posts

May 23, 2017 at 4:18 pm

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

May 23, 2017 at 5:07 pm

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)

May 23, 2017 at 7:50 pm

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

May 23, 2017 at 10:43 pm

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

June 12, 2017 at 9:01 pm

Many thanks!
marius