在 PowerShell 中显式 return 多行计算值 属性

Explicitly return value in multiline calculated property in PowerShell

在 PS 中,当使用 Select-Object 时,-Property 参数“将属性指定为 select”:

The value of the Property parameter can be a new calculated property. To create a calculated, property, use a hash table.

Valid keys are:

  • Name: <string>
  • Expression: <string> or <script block>

作为起点,这里有一个

$person = [pscustomobject]@{
    FirstName = "Kyle";
    LastName = "Mit"
}

以下计算得到的 属性 工作正常:

$person | Select-Object 'FirstName', 'LastName', 
            @{
                Name="FullName";
                Expression= { "$($_.FirstName) $($_.LastName)" }
            }

以下 return 正确的是:

FirstName LastName FullName
--------- -------- --------
Kyle      Mit      Kyle Mit

但是,我正在尝试构建一个计算的属性,它需要一些复杂的逻辑并且需要多行来实现。一旦我在表达式中有另一个 return 值,两个值都是 returned.

所以下面的查询会return FullName as { false, "Kyle Mit" }

$person | Select-Object 'FirstName', 'LastName', 
            @{
                Name="FullName";
                Expression= { 
                    "test" -eq "example"
                    return "$($_.FirstName) $($_.LastName)" 
                }
            }

return以下是:

FirstName LastName FullName         
--------- -------- --------         
Kyle      Mit      {False, Kyle Mit}

但我试图明确 return 只是最后一个陈述。用 ; 分隔或使用 return 似乎没有帮助。

有什么想法吗?

Out-Null扔掉不需要的表达式结果即可。:

$person | Select-Object 'FirstName', 'LastName',
             @{
                 Name="FullName";
                 Expression= {
                     "test" -eq "example" | out-null
                    return "$($_.FirstName) $($_.LastName)"
                 }
             }