0

使用自定义 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 中可行吗?

谢谢。

4

3 回答 3

2

我会这样使用Invoke-Expression

function ExecBoolean ([string] $sFunctionName)
{   
    Write-Host "Array Length = " $args.Length ", Items = [" $args[0..($args.Length - 1)] "]"
    $oResult = Invoke-Expression "$sFunctionName  $($args -join ' ')"
    # 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
    }
}
ExecBoolean Foo String1 1

注意:

  1. 我使用$args哪个更舒服,因为您不会将参数作为数组传递。但是,您也可以$oArgs毫无问题地使用 your (唯一重要的是带有 的行Invoke-Expression)。
  2. 这仅适用于简单类型(字符串、整数、...),但不适用于 eg FileInfo,因为对象在$($args -join ' ').
  3. 还有一种选择,但是太冗长了:ExecBoolean Foo @{sTest="String1"; iTest=1}. 因此,您将在哈希表中传递参数。当然,您需要更改 Foo 以接受哈希表。在这种情况下,您可以传入任何类型,因为您可以使用&运算符调用 Foo。
  4. 见下文

由于限制,我不会推荐这种方法(但可能会发生其他人可能会提出更好的解决方案)。
如果您只是想确保 Foo 不返回任何输出,您可以创建一个脚本来解析其他调用 Foo 的脚本并检查对“Foo”的每次调用是否必须以$null =.

如果您切换到 PowerShell V2,则有更好的方法称为 splatting。有关更多信息,请查看如何以及为什么使用 Splatting(传递 [switch] 参数)

于 2010-02-16T06:21:27.050 回答
0
$oResult = & $sFunctionName $oArgs[0..($oArgs.Length - 1)]

在这里,您只向函数传递了一个参数——一个数组——所以第二个参数Foo默认为0.

如果您只想丢弃语句/表达式的输出,有办法做到这一点,例如将其管道传输到Out-Null或“强制转换”到void.

于 2010-02-15T23:16:57.423 回答
-1

就个人而言,我只会使用:

functionName -as [bool]

这会将函数的结果强制转换为布尔值。

以后的可读性要高得多。

希望这可以帮助

于 2010-02-16T21:27:00.247 回答