powershellpowershell-remoting

When capturing the return value of Invoke-Command I don't see the output of the commands


In a PowerShell script, I have something like this:

$Session = New-PSSession -ComputerName "WSEM00G2NZ" -Credential $credObject
Invoke-Command -Session $Session -Scriptblock {
    python path\to\script\print_stuff.py
}
Remove-PSSession -Session $Session

I.e. it runs a python script on a remote machine. Running the script, I can see the output from the python script. Now, I would like to capture a return value, but if I change the PowerShell script to the following, I don't see the output of the python script anymore.

$Session = New-PSSession -ComputerName "WSEM00G2NZ" -Credential $credObject
$returnedValue = Invoke-Command -Session $Session -Scriptblock {
    python path\to\script\print_stuff.py
}
Remove-PSSession -Session $Session

Why is this, and how can I both capture a return value, and have the output from the python script be visible on screen?


Solution

  • Use the -OutVariable common parameter to store the output from Invoke-Command in a variable while still sending it downstream:

    Invoke-Command -Session $Session -Scriptblock {
        python path\to\script\print_stuff.py
    } -OutVariable returnValue
    

    Now you'll get the output on screen as it's sent and have a copy stored in $returnValue