3

In PS, when using Select-Object, the -Property param "specifies the properties to 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>

As an starting point, here's an anonymous object

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

The following calculated property works just fine:

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

Which correctly returns the following:

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

However, I'm trying to build a calculated property that takes some complicated logic and requires multiple lines to implement. As soon as I have another return value inside the expression both values are returned.

So the following query will return FullName as { false, "Kyle Mit" }

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

Which returns the following:

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

But I'm attempting to explicitly return just the last statement. Delimiting with ; or using return doesn't seem to help.

Any ideas?

Community
  • 1
  • 1
KyleMit
  • 30,350
  • 66
  • 462
  • 664
  • not sure what is your logic... I mean... u're testing something then returning something... why to do that that way? use `if`? and return 2 different answers? – Flash Thunder Jan 24 '20 at 17:45
  • @FlashThunder, agreed - it's a weird case. When [using `-matches`](https://stackoverflow.com/a/59900840/1366033), powershell will [create an automatic variable named `$Matches`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7#matches) as a side-effect. So the original expression will return `true` or `false`, but what I'm after is the variable introduced once that's called. – KyleMit Jan 24 '20 at 17:50
  • For `-matches` you probably still want to use `if`: `if($something -match "regexp") { $Matches[0] } else { '' }`, as otherwise the `Matches` variable might return unrelated data in case of no match. – Nickolay May 10 '20 at 15:00

1 Answers1

3

Just toss out the unwanted expression result with Out-Null.:

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