我有一个 PowerShell 脚本(.ps1),它会执行其他具有返回值的 PowerShell 脚本。
我使用以下命令调用该脚本:
$result = Invoke-Expression -Command ".\check.ps1 $fileCommon"
Write-Output $result
输出仅包含具有其他脚本但不是$true
或$false
的返回值为Write-Ouput
。
我该如何捕获来自其他脚本的返回值?
我有一个 PowerShell 脚本(.ps1),它会执行其他具有返回值的 PowerShell 脚本。
我使用以下命令调用该脚本:
$result = Invoke-Expression -Command ".\check.ps1 $fileCommon"
Write-Output $result
输出仅包含具有其他脚本但不是$true
或$false
的返回值为Write-Ouput
。
我该如何捕获来自其他脚本的返回值?
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
指的是父级(调用者)作用域,因此您可以从调用代码中直接读取它。
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
$result
也会包含&
字符。为什么会这样? - Riccardo&
。抓取元素[1]就可以解决问题了! - Riccardo