You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
multi-types instead of ArgumentTransformtionAttribue #12359
with ParameterSets and ArgumentTransformtionAttribue we can change the type of one or more attribute but its lots of typing and sometimes its not easy
Given the dynamically typed nature of Powershell there are lots of cases where multi-types can be useful. multi types are a collection of two or more types which indicate that either one of those can be used.
# prototype
function foo {
param(
[unionType('int','datetime','string')]
$myhappyparam
)
When would you use this in a practical case? PowerShell is pretty permissive when it comes to converting types, but in general I'd pretty much expect that you're only going to end up duplicating code that would otherwise go in the transformation attribute, so I'm not sure what this would really be adding overall?
Right but with that attribute you're transforming it into the real expected type. Here it's just going to be any one of those without any transformation. So since $module will either be string or PSModuleInfo, can you give an example of how you would expect interacting with it to look?
Says "Convert P1 to a string" , "Convert P2 to an int" and "Convert p3 to a file"
The third case does some really stupid things (like creating a reference to a non-existent read only file in \windows\system).
If you say $p4 might be a string or an int , what does it do with 3.14 ? Make it a "3.14" or 3
[int]$p2 says if it is a string try to make it an int. If that fails we get an error.
If you want to say $P might be a name, and ID or an object (which is good !) then you specify no conversion attribute and check inside the function to see what you were passed and proceed accordingly.
pseudo-code if string then ... else if PSmoduleInfo ....
If you need to do that logic manually anyway, I think typing the parameter as [psobject] will do what you want. I could see the value in an attribute that describes the types that a [psobject] typed parameter can accept, but if it was anything other than purely documentation it would make parameter binding really hard to reason about.
sorry for my english
No worries, your english is excellent 🙂
Reacted by Rain Sallow (/u/ta11ow), p0W3RH311 and Michael Klement
(a) Making argument type transformation easier - where, as with ArgumentTransformationAttribute, you always end up with the single declared parameter type.
Taking the System.Management.Automation.PSModuleInfo / string example, I can see how it would be nice to have a simpler way to implement a transformation, namely via a script block:
functionfoo {
param(
# Wishful thinking: If a [string] with a module name or path is given, # transform it to a PSModuleInfo instance.
[Transform([string], { Get-Module-ListAvailable $_ })]
[System.Management.Automation.PSModuleInfo] $Module
)
}
(Of course, you could argue that [System.Management.Automation.PSModuleInfo] '/path/to/module' should be supported by default, but that's a separate issue.)
(b) Allowing a parameter to be limited to a fixed set of types, with command-internal logic to examine the type ultimately passed.
Given the manual effort needed to examine the type inside the function anyway, and given Patrick Meinecke (@SeeminglyScience)'s point about how enforcing the set of types would make parameter binding hard to reason about, I think this would call for a different solution:
Of course, that's what parameter sets are for - but implementing this logic is currently quite cumbersome.
For instance, the following implements two mutually exclusive, positional parameters that target something either by a numeric ID or a name string, so that you can call foo 42 or foo bar, and the former will bind to -ID, the latter to -Name (as an aside: Wait-Process already works that way, but not Get-Process / Stop-Process - see #6551).
why [psobject] work and the baseobject [object] not work ?
[object] would work, and in fact I suggest using it rather than [psobject], because from a scripter's perspective [psobject] should really be considered an invisible helper type not to be used directly.
[object] would work, and in fact I suggest using it rather than [psobject], because from a scripter's perspective [psobject] should really be considered an invisible helper type not to be used directly.
I usually recommend psobject because in some circumstances object can strip ETS properties, and in others it can result in (a very minor) amount of overhead when unwrapping and rewrapping. Plus that's typically what cmdlets type their parameters as so I like the consistency.
(If what was originally discussed here is to go anywhere, I feel (a) and (b) would have to become new issues anyway, so I hope it's OK to continue the tangent here):
I think the presence of [psobject] in PowerShell code is ultimately more confusing and harmful than beneficial.
Even in cmdlets I wish parameters - and especially output objects - weren't PSObjects - see #5551 and #5579.
Note that not typing a parameter does not result in an extra [psobject] wrapper.
That is, omitting a type is equivalent to [object] typing, not [psobject]:
I think the presence of [psobject] in PowerShell code is ultimately more confusing and harmful than beneficial.
Eh I see where you're coming from but I disagree. I remember very early on just thinking "oh it's a PowerShell object, it makes objects do PowerShell things". I know that's just anecdotal but I don't think most ps users would think about it much last past that. Though I could understand it being confusing for C# folks maybe.
Are there still cases where they get stripped?
The one that comes to mind is method parameters where the object will not be rehydrated the same (such as when StoreTypeNameAndInstanceMembersLocally is true). I believe there are more, but none other readily remember-able.
In that example only certain types and pso instances will be stripped of ETS properties because in most cases they will be rehydrated correctly. That said, if the method is binary it will not. That's why PSSerializer.Serializealways strips ETS.
The reason for that (and the reason it can't be fixed) is because most dotnet API's have no awareness of psobject. They won't know that they need to (or if they don't need to) unwrap it. They also don't typically know how to enumerate the properties since just using straight up reflection won't yield much useful.
Is it super likely that you'll ever run into one of these scenarios? Nah, but if it does it'll be real hard for most to troubleshoot and I personally don't think there's a downside.
I don't think most ps users would think about it much last that.
With the presumably accidental extra words in that sentence I'm not sure I got the gist of this. Did you mean to say that most PS users don't think about it much and are accustomed to using [psobject]?
I know that historically[psobject] was often used, notably with New-Object PSObject - before the [pscustomobject] @{ ... } syntax sugar was introduced in v3. Even before that, New-Object PSCustomObject would have made more sense conceptually.
Still, I think we would benefit in the long run if [psobject] became a truly invisible, transparent-to-the-scripter type. The way it currently peeks from behind the curtain - situationally, in ways that are virtually unpredictable to the casual user - will remain a pain point.
In that vein (thanks for the method example): Do you think it's possible in principle to make a non-breaking change that prevent the occasional loss of ETS member without having to use [psobject] variables explicitly?
In that example only certain types and pso instances will be stripped of ETS properties
What causes the loss with $PROFILE, specifically? Looking at the source code, it appears not to use StoreTypeNameAndInstanceMembersLocally
Also, StoreTypeNameAndInstanceMembersLocally appears to be a v2 legacy feature anyway (see #7768 (comment)), and its continued use causes the problem in #7937, for instance.
I think the larger point is that attaching ETS instance members to strings and value types is generally a bad idea, and the $PROFILE implementation - a string with NoteProperty members - always struck me as awkward and obscure.
If a [string] instance with NoteProperty members is the only case where [psobject] is needed, I'd say that hardly warrants its use.
I don't see where in that issue (including the linked comment) where that's said, did you link the right one?
in V3 when we changed the underlying representation of instance members.
That suggests to me that a better mechanism was introduced that supersedes the old one , and the linked comment details the improvements.
Conversely, the old mechanism is both obscure and can cause problems, as #7937 demonstrates, and as summarized int this comment by someone I implicitly trust (just kidding):
Generally, the - seemingly legacy - mechanism of associating instance member with a - usually invisible - [psobject] wrapper rather than the wrapped object itself strikes me as highly obscure
Let me ask the opposite: why do you think it's still useful (leaving aside true edge cases)?
Let's try to narrow this down: Is [string] the only type to which that applies?
Think so
I think the larger point is that attaching ETS instance members to strings and value types is generally a bad idea, and the $PROFILE implementation - a string with NoteProperty members - always struck me as awkward and obscure.
🤷 won't stop folks from doing it.
If a [string] instance with NoteProperty members is the only case where [psobject] is needed
Also pso's with StoreTypeNameAndInstanceMembersLocally.
I'd say that hardly warrants its use.
Between the two psobject handles some niche cases better. If you personally don't like psobject for style or philosophical reasons, yeah the world for sure isn't going to end if you use object.
in V3 when we changed the underlying representation of instance members.
That suggests to me that a better mechanism was introduced that supersedes the old one , and the linked comment details the improvements.
He's saying that they added resurrection tables and then describes the benefits of them. StoreTypeNameAndInstanceMembersLocally is how you purposefully skip resurrection tables.
Let me ask the opposite: why do you think it's still useful (leaving aside true edge cases)?
No matter how I feel about it personally, it's still used.
I do kinda wish it was used more though. Resurrection is really annoying with types that are cached for instance. For example, making a provider that outputs Type objects, now every literal has PSPath attached to it. You could argue that you should create a wrapper type, but then you have to reimplement all of the methods on Type, etc. Or lets say you're just trying to add a property or type name for formatting, now everywhere that instance is used is changed. It's like global variables imo, I don't want to dirty up global scope.
For function and script parameters (the premise of this issue) omitting a type constraint or using [object] works fine in all cases - ETS members are never lost, so there's no need for [psobject].
For method parameters in PowerShell classes, omitting a type constraint or using [object] works fine, except in the following edge case:
PSObject instances that have instance ETS members and whose private StoreTypeNameAndInstanceMembersLocally property is true, i.e. whose ETS instance members are associated with the incidental PSObject wrapper rather than the wrapped objects themselves (via the v3+ resurrection tables); to support such objects, you must declare your parameter as [psobject] (which means that arguments that aren't yet [psobject]-wrapped will be, which can have behavioral implications - see Objects are situationally invisibly [psobject]-wrapped, sometimes causing unexpected behavior. #5579). Such objects are created under the following conditions:
Invariably, for technical reasons (the CLR's string interning), when attaching ETS instance members to [string] instances (actually, it seems that the resurrection tables are also used in this case, only with the [psobject] wrapper rather than the [string] instance as the lookup key, but the net effect is the same: the ETS instance members are attached to the wrapper).
For the same reasons it is not advisable to add instance ETS members to instance of .NET primitive types (such as most number types, [char], and [bool]) (even though they are passed through to methods); additionally, the engine caches certain numbers so $v = 42; $v | Add-Member foo bar doesn't just make $v.foo return 'bar', but also associates the property with the literal: & { param($p) $p.foo } 42 then prints 'bar'.
Potentially, by engine-internal code that opts-into the v2 behavior; the - sensible - default in v3+ is to leave StoreTypeNameAndInstanceMembersLocally at false, i.e. to associate the ETS instance members with the the wrapped object themselves. (Note that user code cannot opt-into v2 behavior, because the static method that creates a PSObject with StoreTypeNameAndInstanceMembersLocally set to true is internal.) See below.
Note that for a method in compiled code the only way to receive an object with ETS members - whether instance or type-level, whether with StoreTypeNameAndInstanceMembersLocally set to true or not - is to declare the parameter as PSObject.
By contrast, a cmdlet's parameters - which are implemented as .NET type properties - do receive PSObject wrappers as such even for object-typed parameters = properties (not just for PSObject-typed ones).
Instances of wrapper-only instance members in the engine code as of PowerShell Core 7.1.0-preview.1 (StoreTypeNameAndInstanceMembersLocally set to true):
Note: Obtained via regex PSObject.AsPSObject([^)]+?,.+?), with false positives weeded out.
Or lets say you're just trying to add a property or type name for formatting, now everywhere that instance is used is changed
The above use avoids that, and constitutes the aforementioned edge case; it is a legitimate use that should have no impact on user code and is unlikely to raise questions, given that the context is for-display formatting.
I do kinda wish it was used more though. Resurrection is really annoying with types that are cached for instance. For example, making a provider that outputs Type objects, now every literal has PSPath attached to it.
I think we can cross that bridge when we get to it. Instance members showing up on cached instances is already a problem with cached number literals, as shown above, but adding ETS instance members to instances of such types is ill-advised anyway.
Overall, I think it is important not to use per-wrapper instance members anymore, so as to spare users the confusion of members disappearing in ways that are hard to reason about and may seem inexplicable altogether to the casual user.
It's technically different, but the behavior described in #4347 sows similar confusion.
In the light of this discussion what is the better (preferred,safe,right...) way of using generic.list? [System.Collections.Generic.List[psobject]] or [System.Collections.Generic.List[object]]?
In compiled code, if you pass something like [System.Collections.Generic.List[psobject]] @(1, 2) to a System.Collections.Generic.List<object>-typed method parameter, that code will see the list elements as [psobject], not [int].
Let me try to summarize at a higher level (my personal assessment):
From the perspective of code written in PowerShell, [psobject] should never have entered the picture: it should always have been an invisible helper type, used only behind the scenes (Compiled (C#) code for cmdlets, by contrast, does need to be aware of PSObject and use it on occasion, but by no means always - see Should all [psobject] cmdlet parameters be changed to [object]? #5551). To put it differently: The presence of [psobject] in Powershell code amounts to a leaky abstraction.
There are unfortunate historic reasons that promoted the visibility and use of PSObject:
Early PowerShell code - before the availability of syntactic sugar [pscustomobject] @{ ... }, which notably does not work in the form [psobject] @{ ... } - often used New-Object PSObject, even though New-Object PSCustomObject would have been the conceptually appropriate form from the beginning.
Syntax diagrams for cmdlets with "untyped" parameters show <PSObject> (which is technically correct, but from a PowerShell user's perspective <Object> would make more sense - it would be a beneficial "lie", just like ([psobject] 42) -is [int] being $true is).
(Note that hidden members such as .psobject are obviously useful for advanced tasks, but, given that they're automatically available on any value directly, they don't require dealing with [psobject] as a whole.)
While [psobject] cannot technically be banished anymore from PowerShell code due to backward compatibility concerns:
we can fix the aforementioned bugs resulting from the conflation of [pscustomobject] and [psobject], as well as the bugs that cause different behavior in the presence of incidental [psobject] wrappers.
we can document that direct use of [psobject] is virtually never necessary (see below), thereby discouraging its use.
Eliminating [psobject] from PowerShell code simplifies the "object ontology" for PowerShell users: Objects fall into only one of two categories:
instances of .NET types that PowerShell optionally decorates with additional members, the implementation of which you needn't know or care about.
dynamically constructed ad hoc objects ("property bags") in the form of [pscustomobject] / System.Management.Automation.PSCustomObject instances.
That both these features are ultimately implemented via [psobject] is purely an implementation detail.
To recap the only scenario in which you currently truly need[psobject] in PowerShell code:
If you define a method in a PowerShell class that accepts what is conceptually a [string] parameter and that parameter needs access to a given string's ETS instance members (which would apply if you pass $PROFILE and need access to the AllUsersAllHosts property, for instance, or if you pass a Get-Content-output string and need access to the .ReadCount property, for instance), you must define that parameter as [psobject].
This conceptually obscure requirement solely exists due to a technical limitation that is outside PowerShell's control.
As stated, [psobject]-wrapped instances of other types work fine (except, potentially, due to the bug described in Select-Object -ExpandProperty hides ETS instance members #7937), and in functions / scripts / script blocks even [string] works fine, so there is never a need to type a parameter [psobject] there.
Reacted by Matthew Gray, metablaster and Brian Scholer
Patrick Meinecke (@SeeminglyScience), per the protocol we had agreed on - expressing an overall sentiment of dissent via a thumbs-down emoji - I've already marked your previous comment accordingly, but, given that the follow-up comments were lengthy, perhaps a focused summary is helpful:
I remember very early on just thinking "oh it's a PowerShell object, it makes objects do PowerShell things".
That something has a long history of usage is not per se justification for continuing that usage.
🤷 won't stop folks from doing it.
Showing indifference toward ill-advised usage is problematic in general, but especially in the context of recommending related usage explicitly on the grounds of accommodating the ill-advised usage.
I do kinda wish it was used more, though.
Advocating for increased use of a feature that represents a step backward and decreases the predictability of the language for end users is problematic.
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commented on Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commented on Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
Activity
vexx32 commentedon Apr 17, 2020
When would you use this in a practical case? PowerShell is pretty permissive when it comes to converting types, but in general I'd pretty much expect that you're only going to end up duplicating code that would otherwise go in the transformation attribute, so I'm not sure what this would really be adding overall?
p0W3RH311 commentedon Apr 17, 2020
for example:
works in all caases
this feature is not to replace paramsets or argument transformer but its more easy less typing...etc
SeeminglyScience commentedon Apr 17, 2020
A
stringand aPSModuleInfoare pretty different. How would you use them as if they were the same?p0W3RH311 commentedon Apr 17, 2020
Patrick Meinecke (@SeeminglyScience)
the idea is like ArgumentTransformtionAttribue transform type of attribbute but in easy way
SeeminglyScience commentedon Apr 17, 2020
Right but with that attribute you're transforming it into the real expected type. Here it's just going to be any one of those without any transformation. So since
$modulewill either bestringorPSModuleInfo, can you give an example of how you would expect interacting with it to look?p0W3RH311 commentedon Apr 17, 2020
the logic in body of this function is same as the logic of body of ArgumentTransformtionAttribue.
we tests the type of $module
pseudo-code
if string then ... else if PSmoduleInfo ....also with parametersets is the same mechanism we tests the parametersets
this is a prototype...maybee samee chaange occuurs...
the goal is to simplify the convertion between multiple type
sorry for my english
jhoneill commentedon Apr 17, 2020
That's not how types work with parameter
Says "Convert P1 to a string" , "Convert P2 to an int" and "Convert p3 to a file"
The third case does some really stupid things (like creating a reference to a non-existent read only file in \windows\system).
If you say $p4 might be a string or an int , what does it do with 3.14 ? Make it a "3.14" or 3
[int]$p2says if it is a string try to make it an int. If that fails we get an error.If you want to say $P might be a name, and ID or an object (which is good !) then you specify no conversion attribute and check inside the function to see what you were passed and proceed accordingly.
SeeminglyScience commentedon Apr 17, 2020
If you need to do that logic manually anyway, I think typing the parameter as
[psobject]will do what you want. I could see the value in an attribute that describes the types that a[psobject]typed parameter can accept, but if it was anything other than purely documentation it would make parameter binding really hard to reason about.No worries, your english is excellent 🙂
p0W3RH311 commentedon Apr 18, 2020
Patrick Meinecke (@SeeminglyScience)
thanks you.
but why [psobject] work and the baseobject [object] not work ?
mklement0 commentedon Apr 18, 2020
It looks like there are two distinct aspects:
(a) Making argument type transformation easier - where, as with
ArgumentTransformationAttribute, you always end up with the single declared parameter type.Taking the
System.Management.Automation.PSModuleInfo/stringexample, I can see how it would be nice to have a simpler way to implement a transformation, namely via a script block:(Of course, you could argue that
[System.Management.Automation.PSModuleInfo] '/path/to/module'should be supported by default, but that's a separate issue.)(b) Allowing a parameter to be limited to a fixed set of types, with command-internal logic to examine the type ultimately passed.
Given the manual effort needed to examine the type inside the function anyway, and given Patrick Meinecke (@SeeminglyScience)'s point about how enforcing the set of types would make parameter binding hard to reason about, I think this would call for a different solution:
Distinct, strongly typed, mutually exclusive parameters.
Of course, that's what parameter sets are for - but implementing this logic is currently quite cumbersome.
For instance, the following implements two mutually exclusive, positional parameters that target something either by a numeric ID or a name string, so that you can call
foo 42orfoo bar, and the former will bind to-ID, the latter to-Name(as an aside:Wait-Processalready works that way, but notGet-Process/Stop-Process- see #6551).That's a lot of ceremony, and I wonder if we should allow a more succinct expression of this concept.
We have thought about this before, namely in the context of this since-withdrawn RFC: https://github.com/PowerShell/PowerShell-RFC/blob/master/X-Withdrawn/RFC0001-Mutual-Exclusion-Parameters-and-Properties.md
[object]would work, and in fact I suggest using it rather than[psobject], because from a scripter's perspective[psobject]should really be considered an invisible helper type not to be used directly.SeeminglyScience commentedon Apr 18, 2020
I usually recommend
psobjectbecause in some circumstancesobjectcan strip ETS properties, and in others it can result in (a very minor) amount of overhead when unwrapping and rewrapping. Plus that's typically what cmdlets type their parameters as so I like the consistency.mklement0 commentedon Apr 18, 2020
(If what was originally discussed here is to go anywhere, I feel (a) and (b) would have to become new issues anyway, so I hope it's OK to continue the tangent here):
I think the presence of
[psobject]in PowerShell code is ultimately more confusing and harmful than beneficial.Even in cmdlets I wish parameters - and especially output objects - weren't
PSObjects - see #5551 and #5579.Note that not typing a parameter does not result in an extra
[psobject]wrapper.That is, omitting a type is equivalent to
[object]typing, not[psobject]:As for ETS members getting stripped; Jason Shirk (@lzybkr) alludes to that here, but I can't actually get that to happen:
Are there still cases where they get stripped?
SeeminglyScience commentedon Apr 18, 2020
Eh I see where you're coming from but I disagree. I remember very early on just thinking "oh it's a PowerShell object, it makes objects do PowerShell things". I know that's just anecdotal but I don't think most ps users would think about it much
lastpast that. Though I could understand it being confusing for C# folks maybe.The one that comes to mind is method parameters where the object will not be rehydrated the same (such as when
StoreTypeNameAndInstanceMembersLocallyis true). I believe there are more, but none other readily remember-able.In that example only certain types and pso instances will be stripped of ETS properties because in most cases they will be rehydrated correctly. That said, if the method is binary it will not. That's why
PSSerializer.Serializealways strips ETS.The reason for that (and the reason it can't be fixed) is because most dotnet API's have no awareness of
psobject. They won't know that they need to (or if they don't need to) unwrap it. They also don't typically know how to enumerate the properties since just using straight up reflection won't yield much useful.Is it super likely that you'll ever run into one of these scenarios? Nah, but if it does it'll be real hard for most to troubleshoot and I personally don't think there's a downside.
mklement0 commentedon Apr 18, 2020
Thanks, Patrick Meinecke (@SeeminglyScience).
With the presumably accidental extra words in that sentence I'm not sure I got the gist of this. Did you mean to say that most PS users don't think about it much and are accustomed to using
[psobject]?I know that historically
[psobject]was often used, notably withNew-Object PSObject- before the[pscustomobject] @{ ... }syntax sugar was introduced in v3. Even before that,New-Object PSCustomObjectwould have made more sense conceptually.Still, I think we would benefit in the long run if
[psobject]became a truly invisible, transparent-to-the-scripter type. The way it currently peeks from behind the curtain - situationally, in ways that are virtually unpredictable to the casual user - will remain a pain point.In that vein (thanks for the method example): Do you think it's possible in principle to make a non-breaking change that prevent the occasional loss of ETS member without having to use
[psobject]variables explicitly?What causes the loss with
$PROFILE, specifically? Looking at the source code, it appears not to useStoreTypeNameAndInstanceMembersLocallyAlso,
StoreTypeNameAndInstanceMembersLocallyappears to be a v2 legacy feature anyway (see #7768 (comment)), and its continued use causes the problem in #7937, for instance.1 remaining item
mklement0 commentedon Apr 18, 2020
As always, I appreciate the deep dive, Patrick Meinecke (@SeeminglyScience).
Let's try to narrow this down: Is
[string]the only type to which that applies?That does appear to be the case:
I think the larger point is that attaching ETS instance members to strings and value types is generally a bad idea, and the
$PROFILEimplementation - a string withNotePropertymembers - always struck me as awkward and obscure.If a
[string]instance withNotePropertymembers is the only case where[psobject]is needed, I'd say that hardly warrants its use.The linked comment states:
That suggests to me that a better mechanism was introduced that supersedes the old one , and the linked comment details the improvements.
Conversely, the old mechanism is both obscure and can cause problems, as #7937 demonstrates, and as summarized int this comment by someone I implicitly trust (just kidding):
Let me ask the opposite: why do you think it's still useful (leaving aside true edge cases)?
SeeminglyScience commentedon Apr 19, 2020
Think so
🤷 won't stop folks from doing it.
Also pso's with
StoreTypeNameAndInstanceMembersLocally.Between the two
psobjecthandles some niche cases better. If you personally don't likepsobjectfor style or philosophical reasons, yeah the world for sure isn't going to end if you useobject.He's saying that they added resurrection tables and then describes the benefits of them.
StoreTypeNameAndInstanceMembersLocallyis how you purposefully skip resurrection tables.No matter how I feel about it personally, it's still used.
I do kinda wish it was used more though. Resurrection is really annoying with types that are cached for instance. For example, making a provider that outputs
Typeobjects, now every literal hasPSPathattached to it. You could argue that you should create a wrapper type, but then you have to reimplement all of the methods onType, etc. Or lets say you're just trying to add a property or type name for formatting, now everywhere that instance is used is changed. It's like global variables imo, I don't want to dirty up global scope.mklement0 commentedon Apr 19, 2020
Let's try to summarize:
For function and script parameters (the premise of this issue) omitting a type constraint or using
[object]works fine in all cases - ETS members are never lost, so there's no need for[psobject].For method parameters in PowerShell classes, omitting a type constraint or using
[object]works fine, except in the following edge case:PSObjectinstances that have instance ETS members and whose privateStoreTypeNameAndInstanceMembersLocallyproperty istrue, i.e. whose ETS instance members are associated with the incidentalPSObjectwrapper rather than the wrapped objects themselves (via the v3+ resurrection tables); to support such objects, you must declare your parameter as[psobject](which means that arguments that aren't yet[psobject]-wrapped will be, which can have behavioral implications - see Objects are situationally invisibly [psobject]-wrapped, sometimes causing unexpected behavior. #5579). Such objects are created under the following conditions:Invariably, for technical reasons (the CLR's string interning), when attaching ETS instance members to
[string]instances (actually, it seems that the resurrection tables are also used in this case, only with the[psobject]wrapper rather than the[string]instance as the lookup key, but the net effect is the same: the ETS instance members are attached to the wrapper).It is generally not advisable to create such wrapped
[string]instances, because the ETS properties are hard to discover, given that the[psobject]wrapper still prints like a string by default; it is unfortunate that the automatic$PROFILEvariable uses this technique; similarly, the strings output byGet-Contentare wrapped this way, currently without an opt-out - see Get-Content is slow on large text files. Could it have a parameter to speed it up by not adding NoteProperties? #7537. Such wrapped strings can conversely surface their ETS instance members in unexpected situations - see ConvertTo-Json: unexpected behavior with objects that have ETS properties (NoteProperty, ScriptProperty) #5797.For the same reasons it is not advisable to add instance ETS members to instance of .NET primitive types (such as most number types,
[char], and[bool]) (even though they are passed through to methods); additionally, the engine caches certain numbers so$v = 42; $v | Add-Member foo bardoesn't just make$v.fooreturn'bar', but also associates the property with the literal:& { param($p) $p.foo } 42then prints'bar'.Potentially, by engine-internal code that opts-into the v2 behavior; the - sensible - default in v3+ is to leave
StoreTypeNameAndInstanceMembersLocallyatfalse, i.e. to associate the ETS instance members with the the wrapped object themselves. (Note that user code cannot opt-into v2 behavior, because the static method that creates aPSObjectwithStoreTypeNameAndInstanceMembersLocallyset totrueisinternal.) See below.Note that for a method in compiled code the only way to receive an object with ETS members - whether instance or type-level, whether with
StoreTypeNameAndInstanceMembersLocallyset totrueor not - is to declare the parameter asPSObject.By contrast, a cmdlet's parameters - which are implemented as .NET type properties - do receive
PSObjectwrappers as such even forobject-typed parameters = properties (not just forPSObject-typed ones).Instances of wrapper-only instance members in the engine code as of PowerShell Core 7.1.0-preview.1 (
StoreTypeNameAndInstanceMembersLocallyset totrue):Note: Obtained via regex
PSObject.AsPSObject([^)]+?,.+?), with false positives weeded out.PowerShell/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs
Line 79 in 022c149
The above use avoids that, and constitutes the aforementioned edge case; it is a legitimate use that should have no impact on user code and is unlikely to raise questions, given that the context is for-display formatting.
PowerShell/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs
Line 536 in 022c149
PowerShell/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs
Line 553 in 022c149
This is the bug reported in #7937.
I think we can cross that bridge when we get to it. Instance members showing up on cached instances is already a problem with cached number literals, as shown above, but adding ETS instance members to instances of such types is ill-advised anyway.
Overall, I think it is important not to use per-wrapper instance members anymore, so as to spare users the confusion of members disappearing in ways that are hard to reason about and may seem inexplicable altogether to the casual user.
It's technically different, but the behavior described in #4347 sows similar confusion.
scriptingstudio commentedon Apr 20, 2020
In the light of this discussion what is the better (preferred,safe,right...) way of using
generic.list?[System.Collections.Generic.List[psobject]]or[System.Collections.Generic.List[object]]?mklement0 commentedon Apr 20, 2020
Use
[System.Collections.Generic.List[object]]- there is no need for[psobject]wrappers around the elements.In PowerShell code, the wrappers will mostly not be noticeable (though can cause side effects, as shown in Objects are situationally invisibly [psobject]-wrapped, sometimes causing unexpected behavior. #5579), but they're unnecessary.
In compiled code, if you pass something like
[System.Collections.Generic.List[psobject]] @(1, 2)to aSystem.Collections.Generic.List<object>-typed method parameter, that code will see the list elements as[psobject], not[int].Let me try to summarize at a higher level (my personal assessment):
From the perspective of code written in PowerShell,
[psobject]should never have entered the picture: it should always have been an invisible helper type, used only behind the scenes (Compiled (C#) code for cmdlets, by contrast, does need to be aware ofPSObjectand use it on occasion, but by no means always - see Should all [psobject] cmdlet parameters be changed to [object]? #5551). To put it differently: The presence of[psobject]in Powershell code amounts to a leaky abstraction.There are unfortunate historic reasons that promoted the visibility and use of
PSObject:The unfortunate technical conflation of
[pscustomobject]and[psobject]: they both point toSystem.Management.Automation.PSObject- even though there is a distinctSystem.Management.Automation.PSCustomObjecttype (see Why is [pscustomobject] the same as [psobject], even though a distinct [System.Management.Automation.PSCustomObject] type exists? #4344). Only the latter should be visible to PowerShell code. The conflation causes a number of problems, such as -as operator does not recognize System.Management.Automation.PSCustomObject instances as such #4343 and Make -is [pscustomobject] and -as [pscustomobject] work meaningfully #11921Early PowerShell code - before the availability of syntactic sugar
[pscustomobject] @{ ... }, which notably does not work in the form[psobject] @{ ... }- often usedNew-Object PSObject, even thoughNew-Object PSCustomObjectwould have been the conceptually appropriate form from the beginning.Syntax diagrams for cmdlets with "untyped" parameters show
<PSObject>(which is technically correct, but from a PowerShell user's perspective<Object>would make more sense - it would be a beneficial "lie", just like([psobject] 42) -is [int]being$trueis).(Note that hidden members such as
.psobjectare obviously useful for advanced tasks, but, given that they're automatically available on any value directly, they don't require dealing with[psobject]as a whole.)While
[psobject]cannot technically be banished anymore from PowerShell code due to backward compatibility concerns:we can fix the aforementioned bugs resulting from the conflation of
[pscustomobject]and[psobject], as well as the bugs that cause different behavior in the presence of incidental[psobject]wrappers.we can document that direct use of
[psobject]is virtually never necessary (see below), thereby discouraging its use.Eliminating
[psobject]from PowerShell code simplifies the "object ontology" for PowerShell users: Objects fall into only one of two categories:instances of .NET types that PowerShell optionally decorates with additional members, the implementation of which you needn't know or care about.
dynamically constructed ad hoc objects ("property bags") in the form of
[pscustomobject]/System.Management.Automation.PSCustomObjectinstances.That both these features are ultimately implemented via
[psobject]is purely an implementation detail.To recap the only scenario in which you currently truly need
[psobject]in PowerShell code:If you define a method in a PowerShell class that accepts what is conceptually a
[string]parameter and that parameter needs access to a given string's ETS instance members (which would apply if you pass$PROFILEand need access to theAllUsersAllHostsproperty, for instance, or if you pass aGet-Content-output string and need access to the.ReadCountproperty, for instance), you must define that parameter as[psobject].As stated,
[psobject]-wrapped instances of other types work fine (except, potentially, due to the bug described in Select-Object -ExpandProperty hides ETS instance members #7937), and in functions / scripts / script blocks even[string]works fine, so there is never a need to type a parameter[psobject]there.scriptingstudio commentedon Apr 20, 2020
Michael Klement (@mklement0) thanks for a detailed response. It is clear and cool.
mklement0 commentedon Apr 21, 2020
I'm glad to hear the comment was helpful, Matthew Gray (@scriptingstudio), and I appreciate the feedback.
Patrick Meinecke (@SeeminglyScience), per the protocol we had agreed on - expressing an overall sentiment of dissent via a thumbs-down emoji - I've already marked your previous comment accordingly, but, given that the follow-up comments were lengthy, perhaps a focused summary is helpful:
That something has a long history of usage is not per se justification for continuing that usage.
Showing indifference toward ill-advised usage is problematic in general, but especially in the context of recommending related usage explicitly on the grounds of accommodating the ill-advised usage.
Advocating for increased use of a feature that represents a step backward and decreases the predictability of the language for end users is problematic.
mklement0 commentedon Apr 21, 2020
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 23, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.