How catch return value in a Powershell script

gtx911 picture gtx911 · May 29, 2018 · Viewed 26.6k times · Source

I have a powershell script (.ps1) that execute other Powershell script that has a return value.

I invoke to the script with this command:

$result = Invoke-Expression -Command ".\check.ps1 $fileCommon"

Write-Output $result

The output is only the Write-Ouput that have the other script but not the return value that is $true or $false.

How can I catch the return from the other script?

Answer

TToni picture TToni · May 29, 2018

The expression behind a return statement in PowerShell gets evaluated like every other expression. If it produces output, it is written to stdout. Your $result receives whatever is written to stdout by the script. If more than one thing is written to stdout, you get these things in an array.

So if your check.ps1 for example looks like this:

Write-Output "$args[0]"
return $false

and you call it with

$result = &".\check.ps1" xxx

then $resultwill be an object array of size 2 with the values "xxx" (string) and "False" (bool).

If you cannot change the script so that is writes only the return value to stdout (which would be the cleanest way), you could ignore everything but the last value:

$result = &".\check.ps1" xxx | select -Last 1

Now $result will contain only "False" as a boolean value.

If you can change the script, another option would be to pass a variable name and set that in the script.

Call:

&".\check.ps1" $fileCommon "result"
if ($result) {
    # Do things
}

Script:

param($file,$parentvariable)
# Do things
Set-Variable -Name $parentvariable -Value $false -Scope 1

The -Scope 1 refers to the parent (caller) scope, so you can just read it from the calling code.