How catch return value in a Powershell script How catch return value in a Powershell script powershell powershell

How catch return value in a Powershell script


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 thingsSet-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.


The proper reliable way to return a value from a script function is through setting a variable. Relying on the position of output is prone to breakage in the future if someone for example adds new output to the streams; Write-Output/Write-Warning/Write-Verbose, etc...

Return is so misleading in script functions, unlike any other language. I saw another mechanism using classes+functions in powershell, but I doubt it's what you are looking for.

function Test-Result{            Param(                $ResultVariableName            ) try{     Write-Verbose "Returning value"     Set-Variable -Name $ResultVariableName -Value $false -Scope 1     Write-Verbose "Returned value"     return $value # Will not be the last output    }    catch{     Write-Error "Some Error"    }    finally{     Write-Output "finalizing"     Write-Verbose "really finalizing"    }#Try these cases $VerbosePreference=ContinueTest-Result $MyResultArray=Test-Result *>&1; $MyResultArray[-1] # last object in the arrayTest-Result "MyResult" *>&1; $MyResult