Select-Object - Keep default columns but add one

Viewed 236

I can use Select-Object to choose which columns to show and even add calculated columns. An example:

gci | select *, @{n='LAS'; e={(Get-Date)-$_.LastAccessTime}}

I want add a calculated column but keep the defaut ones. Without the * wildcard I only get my calculated property. With it I get everything. The only workaround I've got to work is to manually list the default property names. Any ideas?

2 Answers

The thing is that that you actually states to display all properties ('*').

So to add to only the standard properties, you first need to get the standard properties.

[string[]]$StdProperties = (Get-ChildItem).PSStandardMembers.DefaultDisplayPropertySet[1].ReferencedPropertyNames

We don't actually want to change the standard property of the objects returned

Get-Childitem | select Name | Get-Member| group TypeName | select Name

Name
----
Selected.System.IO.DirectoryInfo
Selected.System.IO.FileInfo

So we just need to expand on that extracted string array with the new property to use.

$StdProperties += 'LAS'

And finally, to put it to use...

Get-ChildItem | select *, @{n='LAS'; e={(Get-Date) - $_.LastAccessTime}} | 
select $StdProperties

Just for fun, building on Abrahams comment, you could do something weird like this:

# get the default properties used on Format-Table
$defaultProps = (((Get-ChildItem | Format-Table | Out-String) -split '\r?\n' | 
                    Where-Object { $_ -match '^\w.*' }) | 
                    Select-Object -First 1) -split '\s+' -ne ''

# now execute the command
Get-ChildItem | Select-Object *, @{n='LAS'; e={(Get-Date)-$_.LastAccessTime}} | 
    Select-Object ($defaultProps + 'LAS') | Format-Table -AutoSize
Related