Difference between [psobject] and New-Object -Ty PSObject

by davidski at 2013-01-01 15:15:14

Can someone point me to the right bit of documentation for understanding how the [psobject] type accelerator differs from using New-Object -TypeName PSObject? Creating custom views (a nifty part of Toolmaking Month of Lunches Chp12), I was stumped why my custom objects weren’t picking up the custom views. By changing my object creation from using [psobject] to the more verbose New-Object syntax, everything works fine. Reverting back to the use of either [psobject] or [pscustomobject] gives the default views (custom views are not picked up). The objects created by the type accelerators return the correct type via get-member, so there’s something more subtle going on here.

I use the type accelerators a lot in my current code so the revelation that these are not equivalent makes me wonder what else I’m messing up.

David
by DonJ at 2013-01-01 15:32:40
I almost never use the accelerators - I’m a big fan of explicits, whereas the accelerators feel more implicit to me. And, obviously, there’s raunchy stuff going on under the hood that I mistrust. Having never, ever, ever used [psobject] myself, I haven’t run into this and am a bit stumped as to why it’d be any different.

I’m an old enough coder that I tend to prefer the most manual approach possible. I took a lot of convincing, for example, to switch to a hashtable for custom object properties instead of successive calls to Add-Member. The former looks a hell of a lot neater and is easier to read, so I eventually let myself be convinced. But I generally come from a very superstitious perspective with stuff, and I prefer to tell the thing what to do rather than let it do it for me a lot of times. Weird, I know.

I’ll ask around, though. Right now the couple of folks I think would know right-off are in heads-down mode, so it might be a bit.
by davidski at 2013-01-01 19:15:35
A quick update, it looks like the [pscustomobject] accelerator works the same as New-Obejct -Type PSObject (both return the same TypeNames and seem to act identically). Using straight [psobject] generates a object of hashtable type, however. Interesting stuff.
by DonJ at 2013-01-02 07:31:36
Keith Hill confirms that [psobject]@{} returns a hash table, but [pscustomobject]@{} returns a PSCustomObject. Views should still work with that if you give it a type name and load the view. The moral, in my book, is don’t use either :).