使用自定义 Powershell 函数会返回所有函数输出。我试图通过编写一个只返回 $true 或 $false 的包装函数来消除这种限制/混乱。
但是,我正在为动态函数调用而苦苦挣扎。. . 专门传递参数。
请注意,函数名称和函数参数都传递给“ExecBoolean”。
代码示例:
# Simplifies calls to boolean functions in Powershells scripts
# Helps solve this problem -> http://www.vistax64.com/powershell/107328-how-does-return-work-powershell-functions.html
function Foo([string]$sTest, [int] $iTest)
{
Write-Host "sTest [" $sTest "]."
Write-Host "iTest [" $iTest "]."
if ($iTest -eq 1)
{
return $true
}
else
{
return $false
}
}
function ExecBoolean ([string] $sFunctionName, [array] $oArgs)
{
Write-Host "Array Length = " $oArgs.Length ", Items = [" $oArgs[0..($oArgs.Length - 1)] "]"
$oResult = & $sFunctionName $oArgs[0..($oArgs.Length - 1)]
# Powershell returns all function output in oResult, just get the last item in the array, if necessary.
if ($oResult.Length -gt 0)
{
return $oResult[$oResult.Length - 1]
}
else
{
return $oResult
}
}
$oResult = ExecBoolean "Foo" "String1", 1
Write-Host "Result = " $oResult
电流输出:
Array Length = 2 , Items = [ String1 1 ]
sTest [ String1 1 ].
iTest [ 0 ].
Result = False
期望的输出:
Array Length = 2 , Items = [ String1 1 ]
sTest [ String1 ].
iTest [ 1 ].
Result = True
这在 Powershell v1.0 中可行吗?
谢谢。