Getting return code from invoke-command

I am confused about the right way to get a return code from a scriptblock called by invoke-command.
My code looks like:

$my_session = new-pssession -computername $my_computer -credential $my_credentials
$my_exit = invoke-Command -Session $my_session -ScriptBlock {
        ...
        ...
        if ($freespace_mb -lt 10000) 
            {
            write-host "Not enpogh disk space"
            $returncode = 2
            $returncode
            exit
            }
        ...
        $a = 10
        $b = 100
        $c = 1000
        ...
        ...
        $returncode = "everything is ok"
        $returncode 
        } 
write-host $my_exit

I would expect that the content of $my_exit would be either 2 or “everything is ok” based on the results of the test about freespace.
I find instead the expected contents plus garbage, maybe coming from the contents of other variables.
What is the right syntax to get what I expect and only what I expect?
Regards
marius

PowerShell doesn’t do “return codes” in the way you’re perhaps thinking. Anything sent to Write-Output (including just “running” a variable by itself) will end up in the output pipeline, which is what gets serialized and returned to Invoke-Command.

For example, instead of:

$returncode = 2
$retuurncode

You’d just

Write-Output 2

I can’t see all of your code, of course, but if you’re getting back something unexpected, it’s because you have other commands writing to the pipeline.

Also, know that PowerShell isn’t a big fan of passing simple values back and forth. It prefers objects.

$out = @{ 'returncode' = 2 }
New-Object -Type PSObject -Prop $out

The resulting object will have a returncode property set to 2. Invoke-Command will add a PSComputerName property to that, indicating which computer the result came from. That’s useful when you target multiple computers. This technique makes it easier to return multiple pieces of information, packed into a single object, or to return multiple objects if needed.

Many thanks!
Marius