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?
The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.
Using the return Keyword in PowerShell The return keyword can appear alone, or a value or expression can follow it. The return keyword alone will return the command line to its previous calling point. The example below uses the return keyword to exit a function if a conditional is met at a specific point.
If you are inside of a function and return a value with the return keyword, the function will return that value and exit the function. The return keyword causes the function to exit after outputting the first process. PowerShell will then generate output for both processes.
The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.
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 $result
will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With