Skip to content

multi-types instead of ArgumentTransformtionAttribue  #12359

Closed

Description

@p0W3RH311

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
  )

}

Activity

  1. added
    Issue-Enhancement
    on Apr 17, 2020
  2. vexx32 commented on Apr 17, 2020

    @vexx32
    Collaborator

    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?

  3. p0W3RH311 commented on Apr 17, 2020

    @p0W3RH311
    Author

    for example:

    function foo {
      param(
        [unionType('string','System.Management.Automation.PSModuleInfo')]
       [parameter(valuefrompipeline)]
        $module
      )
      proceess {
    
         # code
      }
    }
    
    

    works in all caases

    PS>  get-module mymodule | foo
    PS> foo -module  mymodule
    PS> 'mymddule'  |  foo
    

    this feature is not to replace paramsets or argument transformer but its more easy less typing...etc

  4. SeeminglyScience commented on Apr 17, 2020

    @SeeminglyScience
    Contributor

    A string and a PSModuleInfo are pretty different. How would you use them as if they were the same?

  5. p0W3RH311 commented on Apr 17, 2020

    @p0W3RH311
    Author

    Patrick Meinecke (@SeeminglyScience)

    the idea is like ArgumentTransformtionAttribue transform type of attribbute but in easy way

  6. SeeminglyScience commented on Apr 17, 2020

    @SeeminglyScience
    Contributor

    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?

  7. p0W3RH311 commented on Apr 17, 2020

    @p0W3RH311
    Author

    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

  8. jhoneill commented on Apr 17, 2020

    @jhoneill

    That's not how types work with parameter

    [String]$p1 
    [int]$p2
    [system.io.file]$p3
    

    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.

  9. SeeminglyScience commented on Apr 17, 2020

    @SeeminglyScience
    Contributor

    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 🙂

  10. p0W3RH311 commented on Apr 18, 2020

    @p0W3RH311
    Author

    Patrick Meinecke (@SeeminglyScience)

    thanks you.
    but why [psobject] work and the baseobject [object] not work ?

  11. mklement0 commented on Apr 18, 2020

    @mklement0
    Contributor

    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 / string example, I can see how it would be nice to have a simpler way to implement a transformation, namely via a script block:

    function foo {
      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:

    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 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).

    function foo {
      [CmdletBinding(DefaultParameterSetName='Name')]
      param(
        [Parameter(Position=0)]
        [int] $ID
        ,
        [Parameter(Position=0, ParameterSetName='Name')]    
        [string] $Name
      )
      "[$ID] [$NAME]"
    }

    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


    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.

    GitHub
    RFC (Request for Comments) documents for community feedback on design changes and improvements to PowerShell ecosystem - PowerShell/PowerShell-RFC
  12. SeeminglyScience commented on Apr 18, 2020

    @SeeminglyScience
    Contributor

    [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.

  13. mklement0 commented on Apr 18, 2020

    @mklement0
    Contributor

    (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]:

    # Ditto with `[object] $p`
    PS> & { param($p) $p -is [psobject] } 42
    False 
    
    # vs.
    PS> & { param([psobject] $p) $p -is [psobject] } 42
    True

    As for ETS members getting stripped; Jason Shirk (@lzybkr) alludes to that here, but I can't actually get that to happen:

    PS> (Get-Item / | add-member -passthru  -NotePropertyName foo -NotePropertyValue bar),
    ('other' | add-member -passthru  -NotePropertyName foo -NotePropertyValue bar),
    (42 | add-member -passthru  -NotePropertyName foo -NotePropertyValue bar),
    ($false | add-member -passthru  -NotePropertyName foo -NotePropertyValue bar) | % {
        & { param($p) $p.foo } $_
      }
    
    # ETS property .foo was passed through in all cases.
    bar
    bar
    bar
    bar

    Are there still cases where they get stripped?

  14. SeeminglyScience commented on Apr 18, 2020

    @SeeminglyScience
    Contributor

    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.

    class Test {
        static [object] GetMembers([object] $obj) {
            return Get-Member -InputObject $obj
        }
    }
    
    [Test]::GetMembers($profile) | ? MemberType -eq  NoteProperty

    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.Serialize always 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.

  15. mklement0 commented on Apr 18, 2020

    @mklement0
    Contributor

    Thanks, Patrick Meinecke (@SeeminglyScience).

    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.

  16. 1 remaining item

  17. mklement0 commented on Apr 18, 2020

    @mklement0
    Contributor

    As always, I appreciate the deep dive, Patrick Meinecke (@SeeminglyScience).

    Strings are treated like that member is true implicitly, probably because of string interning.

    Let's try to narrow this down: Is [string] the only type to which that applies?
    That does appear to be the case:

    class Test {
        static [object] GetMembers([object] $obj) {
            return Get-Member -InputObject $obj
        }
    }
    
    # .foo resurfaces; ditto with `$true | Add-Member ...`
    [Test]::GetMembers((42 | Add-Member foo bar -PassThru)) | ? MemberType -eq  NoteProperty

    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?

    The linked comment states:

    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)?

  18. SeeminglyScience commented on Apr 19, 2020

    @SeeminglyScience
    Contributor

    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.

    The linked comment states:

    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.

  19. mklement0 commented on Apr 19, 2020

    @mklement0
    Contributor

    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:

      • 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).

        • 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.

    var obj = PSObject.AsPSObject(errorRecord, storeTypeNameAndInstanceMembersLocally: true);

    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.

    PSObject expandedObject = PSObject.AsPSObject(r.Result, true);

    PSObject expandedObject = PSObject.AsPSObject(expandedValue, true);

    This is the bug reported in #7937.


    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.

  20. scriptingstudio commented on Apr 20, 2020

    @scriptingstudio

    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]]?

  21. mklement0 commented on Apr 20, 2020

    @mklement0
    Contributor

    Use [System.Collections.Generic.List[object]] - there is no need for [psobject] wrappers around the elements.


    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:

    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.

  22. scriptingstudio commented on Apr 20, 2020

    @scriptingstudio

    Michael Klement (@mklement0) thanks for a detailed response. It is clear and cool.

  23. mklement0 commented on Apr 21, 2020

    @mklement0
    Contributor

    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:

    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.

  24. mklement0 commented on Apr 21, 2020

    @mklement0
  25. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    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.

  26. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    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.

  27. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    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.

  28. added
    Resolution-No Activity
    on Nov 16, 2023
  29. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementResolution-No Activity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions