Wednesday, March 25, 2009

Strange Select-Object Behavior in PowerShell V2 CTP3

In PowerShell v1, the rules are as follows -

  • Select-Object used with –first or –last do not change the object type of the objects passing through
  • Select-Object selecting properties or adding changes the object type to PSCustomObject

Proof -

PS> gps -id $pid | Get-Type # Normal
System.Diagnostics.Process
PS> gps -id $pid | select name,ws | Get-Type # PSCustomObject
System.Management.Automation.PSCustomObject
PS> gps -id $pid | select name,ws | select | Get-Type # PSCustomObject
System.Management.Automation.PSCustomObject
PS> gps -id $pid | select * | Get-Type # Normal (errors are left out)
System.Management.Automation.PSCustomObject
PS> gps -id $pid | select | Get-Type # Normal
System.Diagnostics.Process



 



In PowerShell V2 CTP3 the rules seem to be -




  • Select-Object used with –first or –last works as in V1


  • Select-Object, selecting properties or adding properties, creates a new type called Selected.<originaltype>


  • Select-Object resulting in a Selected.<type> will be turned into a Selected.System.Management.Automation.PSCustomObject! Very strange and very problematic in real-life use



Examples, showing it -




PS> gps -id $pid | Get-Type # normal
System.Diagnostics.Process
PS> gps -id $pid | Select name,ws | Get-Type # Selected.<type>
Selected.System.Diagnostics.Process
PS> gps -id $pid | Select name,ws | Select | Get-Type # Selected...PSCustomObject
Selected.System.Management.Automation.PSCustomObject
PS> gps -id $pid | select | Get-Type # normal
System.Diagnostics.Process
PS> gps -id $pid | select | select | Get-Type # normal
System.Diagnostics.Process
PS> gps -id $pid | select -f 1| select | Get-Type # normal
System.Diagnostics.Process
PS>



 



PS. Get-Type is not a built-in, but this function -




function Get-Type($inputObject) {
process { if ($_ -is [object]) {$_.PSTypeNames[0] } }
end { if ($inputObject -is [object]) { $inputObject.PSTypeNames[0] } }
}

No comments: