powershell - boolean 变量作为 Object[] 返回

标签 powershell boolean return-value

我有一个返回 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/

相关文章:

mysql - 为什么 MySQL SLEEP() 函数返回 0?

perl - 当我使用非零参数显式调用 exit 时,为什么我的 Perl 脚本会返回零返回码?

windows - 我可以在不使用密码的情况下检查加密的 zip 存档的内容吗?

loops - 使用 Windows PowerShell 脚本并行编译 LaTeX 文件

powershell - 无法通过插值评估 Powershell 密码

powershell - 登录后 Azure 凭据不可用

json - 如何从 perl 脚本发送 boolean 值而不将它们转换为字符串

ios - 如何检查 Objective C BOOL 变量的 True 或 False

python - 什么会阻止过滤器返回 0?

c++ - 函数原型(prototype)的返回值