Search code examples
powershellcalculated-fieldselect-object

Select-Object calculated property from variable


I'm aware that we can specify a comma-separated string[] of properties in a variable to the Select-Object -Property parameter. However, I'm trying to include calculated properties in that variable. Tried adding it by enclosing them in single-quotes / double-quotes like,

  1. $selectProps = "distinguishedname", '@{n="lastlogontimestamp";e={[datetime]::FromFileTime($_.lastlogontimestamp).ToString()}}'

    and

  2. $selectProps = "distinguishedname","@{n=`"lastlogontimestamp`";e={[datetime]::FromFileTime(`$_.lastlogontimestamp).ToString()}}"

    but to no avail. Any help will be much appreciated.


Solution

  • If you put a string in a variable you should wrap that in quotes. But as the hashtable is not a string you don't have to put it in quotes. ;-)

    $selectProps = @(
        'distinguishedname',
        @{ Name = 'lastlogontimestamp'; Expression = { [datetime]::FromFileTime($_.lastlogontimestamp).ToString() } }
    )
    

    It would work without wrapping the array in @() ... that's just a visual support to make it easier readable.

    If you want to add more than one array with calculated properties to your Select-Object command you can add them together like this for example:

    Select-Object -Property ($SelectProps + $SelectProps2)