如何在Powershell脚本中捕获返回值

25

我有一个 PowerShell 脚本(.ps1),它会执行其他具有返回值的 PowerShell 脚本。

我使用以下命令调用该脚本:

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

Write-Output $result

输出仅包含具有其他脚本但不是$true$false的返回值为Write-Ouput

我该如何捕获来自其他脚本的返回值?

2个回答

35
return "Hello World"

Then your $result will contain the string "Hello World".

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

然后你使用以下代码进行调用:

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

那么$result将会是一个大小为2的对象数组,其值为"xxx"(字符串)和"False"(布尔值)。

如果你不能修改脚本使其仅将返回值写入标准输出流(这将是最干净的方式),你可以忽略除了最后一个值以外的所有内容:

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

现在$result将只包含布尔值"False"。

如果可以更改脚本,则另一种选项是传递变量名称并在脚本中设置它。

调用:

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

脚本:

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

-Scope 1 指的是父级(调用者)作用域,因此您可以从调用代码中直接读取它。


$result 也会包含 & 字符。为什么会这样? - Riccardo
好的,看起来被调用的脚本将返回一个数组,其第一个元素是&。抓取元素[1]就可以解决问题了! - Riccardo

1
适当可靠的从脚本函数返回值的方式是通过设置变量。依赖输出位置容易在未来出现问题,例如如果有人向流添加新的输出; Write-Output/Write-Warning/Write-Verbose等...。
与其他语言不同,Return在脚本函数中非常误导人。我看到另一种使用powershell中类+函数的机制,但我怀疑这不是你要找的。
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=Continue

Test-Result 

$MyResultArray=Test-Result *>&1; $MyResultArray[-1] # last object in the array

Test-Result "MyResult" *>&1; $MyResult

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接