我有一个返回 boolean 变量的函数
function test ($param1, $param2)
{
[boolean]$match=$false;
<# function logic #>
return $match
}
当我尝试在变量 $retByFunct=testing $param1 $param 2 中捕获函数调用时
我将 $retByFunct 作为对象数组。如果我尝试强制 $retByFunct 为 boolean 变量,即 [boolean] $retByFunct=testing $param1 $param 2,我会收到以下错误。
Cannot convert value "System.Object[]" to type System.Boolean
我在返回之前检查了 $match.GetType() 。控制台说它是一个 boolean 值,所以我很困惑为什么在函数调用之后它被转换为一个对象数组。
我知道某些集合对象会发生这种情况,并且有解决方法,但是如何处理变量的情况?
最佳答案
正如@mjolinor 所说,您需要显示其余代码。我怀疑它在某处的成功输出流上生成输出。 PowerShell 函数返回该流上的所有输出,而不仅仅是 return
关键字的参数。从 documentation :
In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the
return
keyword.
之间没有区别
function Foo {
'foo'
}
或者
function Foo {
'foo'
return
}
或者
function Foo {
return 'foo'
}
上述每个函数在调用时都返回字符串
foo
。额外的输出导致返回的值是一个数组,例如:
function Foo {
$v = 'bar'
Write-Output 'foo'
return $v
}
此函数返回一个数组
'foo', 'bar'
。您可以通过将其重定向到
$null
来抑制不需要的输出:function Foo {
$v = 'bar'
Write-Output 'foo' | Out-Null
Write-Output 'foo' >$null
return $v
}
或者通过在变量中捕获它:
function Foo {
$v = 'bar'
$captured = Write-Output 'foo'
return $v
}
关于powershell - boolean 变量作为 Object[] 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866021/