Getting return code from invoke-command

Welcome Forums General PowerShell Q&A Getting return code from invoke-command

This topic contains 2 replies, has 2 voices, and was last updated by

1 year, 10 months ago.

  • Author
  • #72280

    Points: 1
    Rank: Member

    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
            $a = 10
            $b = 100
            $c = 1000
            $returncode = "everything is ok"
    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?

  • #72299

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    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

    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.

  • #72682

    Points: 1
    Rank: Member

    Many thanks!

The topic ‘Getting return code from invoke-command’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort