powershellmeasure-object

How to exclude a property from 'Measure-Object' in PowerShell?


Function returns the employee name and 3 dates, one for each last site visit. I need to show the name along with whichever date is the most recent of the 3.

$results = get-SiteVisits -Properties Name,Site1,Site2,Site3

$results | ForEach-Object {$_ | Select-Object -Property *, @{Name='MaxValue';Expression={($_.PSObject.Properties.Value | Measure-Object -Maximum).Maximum}}}

What I am looking for...

Name     : MARTHA
Site1    : 4/24/2023
Site2    : 4/23/2023
Site3    : 4/25/2023
MaxValue : 4/25/2023

Name     : JOHN
Site1    : 4/18/2023
Site2    : 4/24/2023
Site3    : 4/21/2023
MaxValue : 4/24/2023

What I am getting...

Name     : MARTHA
Site1    : 4/24/2023
Site2    : 4/23/2023
Site3    : 4/25/2023
MaxValue : MARTHA

Name     : JOHN
Site1    : 4/18/2023
Site2    : 4/24/2023
Site3    : 4/21/2023
MaxValue : JOHN

How do I exclude the Name from the MaxValue expression, so I just get the most recent date?


Solution

  • You could use the PSMemberInfoCollection<T>.Match Method which supports wildcards, i.e.:

    [pscustomobject]@{
        Name  = 'MARTHA'
        Site1 = '4/24/2023'
        Site2 = '4/23/2023'
        Site3 = '4/25/2023'
    } | Select-Object -Property *, @{
        Name       = 'MaxValue'
        Expression = {
            ($_.PSObject.Properties.Match('Site*').Value | Measure-Object -Maximum).Maximum
        }
    }
    

    As you may note, the ForEach-Object in your code could be removed, Select-Object already handles pipeline processing:

    Get-SiteVisits -Properties Name, Site1, Site2, Site3 | Select-Object -Property *, @{
        Name       = 'MaxValue'
        Expression = {
            ($_.PSObject.Properties.Match('Site*').Value | Measure-Object -Maximum).Maximum
        }
    }