从多个 return 值中选择

Choose from multiple return values

当我有一个函数,它使用多个 Write-Output 命令和 return 的单个数字时,如何在函数调用代码中获取数字值? 据我所知,行

[int] $var = Get-MyNumber(...)

给我报错

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32"".

可能是因为 PowerShell return 将对象数组(包含 Write-Output 消息)返回给调用者代码,其中对 [int] 类型变量的赋值失败。明白了。

现在,我如何告诉 PowerShell 我只对来自函数 return 的单个值感兴趣,该值的类型为 [int].

顺便说一句,我不想​​通过索引 return 数组来选择输出,因为我可以通过添加另一个 Write-Output 行来弄乱 return 数组中的索引。 (由于代码维护,这迟早会发生)。

代码

function f1() {
    Write-Output "Lala"
    return 5
}

[int] $x = f1
Write-Output $x

导致同样的错误。

我从您的编辑中看到您正在使用 Write-Output 来显示状态消息。

您应该为此使用 Write-Host,或者如果您使用的是 advanced function, I would recommend using Write-Verbose and calling the function with -Verbose when you want to see the messages (see about_CommonParameters)。

更新代码:

function f1() {
    Write-Host "Lala"
    return 5
}

[int] $x = f1
Write-Host $x

高级函数示例

function f1 {
[CmdletBinding()]
param()

    Write-Verbose "Lala"
    return 5
}

$x = f1
# The "Lala" message will not be seen.

$x = f1 -Verbose
# The "Lala" message will be seen.

为什么 Write-Output 似乎在函数之外工作:

Write-Output 将输入对象传递给调用者。对于直接在主机中执行的代码,而不是在函数或 cmdlet 中执行的代码,调用者是主机,主机决定如何处理它。在 powershell.exe(或 ISE)的情况下,显示它。

Write-Host 另一方面,总是写入主机;它不会将任何内容传回给调用者。

另请注意,Write-Output 基本上是可选的。以下几行是等效的:

Write-Output $x
$x