I mostly like the way Select-Object allows you to create custom objects and properties. However, I really wish it was simpler to create properties with ScriptBlock values without the lengthy Hashtable definition.
If only Select-Object would implement something like this so you can define a property ScriptBlock without the long Hashtable definition. Similar to how this custom function I wrote allows you to define a property name as the Key of the Hashtable and the value as the ScriptBlock or name of the property.
Wishlists are usually wishful thinking, there are probably reasons why Select-Object behaves like it does, it isn't that bad since you can short-hand the keys but it just doesn't seem as fluid. Here is to wishing for a better Select-Object.
If only Select-Object would implement something like this so you can define a property ScriptBlock without the long Hashtable definition. Similar to how this custom function I wrote allows you to define a property name as the Key of the Hashtable and the value as the ScriptBlock or name of the property.
Wishlists are usually wishful thinking, there are probably reasons why Select-Object behaves like it does, it isn't that bad since you can short-hand the keys but it just doesn't seem as fluid. Here is to wishing for a better Select-Object.
- function ConvertTo-PSCustomObject {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter(Mandatory = $true, Position = 0)]
- [Array] $Property,
- [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
- $InputObject
- )
- begin {
- $Properties = $Property |% {
- if ($_ -is [Hashtable]) {
- $_.GetEnumerator() |% {
- if ($_.Value -is [ScriptBlock]) {
- @{Name="$($_.Key)";Expression=$_.Value}
- } else {
- @{Name="$($_.Key)";Expression=[ScriptBlock]::Create("`$_.'$($_.Value)'")}
- }
- }
- } else {
- $_
- }
- }
- }
- process {
- $InputObject | Select-Object -Property $Properties
- }
- }
- gci $ENV:TEMP -Directory | ConvertTo-PSCustomObject Extension,@{FileName='Name'},@{Age={(Get-Date) - $_.CreationTime}}
I have a similar request for PSCustomObject literals! I made a Gist to demonstrate how this would work by creating a new function called New-PSObject but it'd be awesome if the object literal syntax also worked.
ReplyDeleteOne difference with mine is it determines whether the scriptblock should be created as a ScriptMethod or ScriptProperty based on the presence of a param() block.
https://gist.github.com/josheinstein/3859588