Skip to content

Select-Object modifies input objects when using both -ExpandProperty and -Property #7768

Closed

Description

@bstrautin

Select-Object should never modify its input objects, but it does, when using both the -ExpandProperty and -Property parameters.

This behavior is documented, but wrong.

Steps to reproduce

$NestedObjects =
  [pscustomobject]@{a=1; b=[pscustomobject]@{c=2}},
  [pscustomobject]@{a=3; b=[pscustomobject]@{c=4}}

$NestedObjects | Out-Host
$NestedObjects | Select-Object a -ExpandProperty b | Out-Host

$NestedObjects | Out-Host
$NestedObjects | Select-Object a -ExpandProperty b | Out-Host

Expected behavior

Re-running the same Select-Object statement should produce the same output, and should not modify its input objects, so the example code should produce the following output:

a b
- -
1 @{c=2}
3 @{c=4}



c a
- -
2 1
4 3


a b
- -
1 @{c=2}
3 @{c=4}



c a
- -
2 1
4 3


Actual behavior

Instead of creating new objects with the appropriate fields, Select-Object modifies the objects specified by -ExpandProperty, which causes an error the second time the same code runs:

a b
- -
1 @{c=2}
3 @{c=4}



c a
- -
2 1
4 3



a b
- -
1 @{c=2; a=1}
3 @{c=4; a=3}


Select-Object : The property cannot be processed because the property "a" already exists.
At line:9 char:18
+ $NestedObjects | Select-Object a -ExpandProperty b | Out-Host
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (@{a=1; b=}:PSObject) [Select-Object], PSArgumentException
+ FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand


Select-Object : The property cannot be processed because the property "a" already exists.
At line:9 char:18
+ $NestedObjects | Select-Object a -ExpandProperty b | Out-Host
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (@{a=3; b=}:PSObject) [Select-Object], PSArgumentException
+ FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand

c a
- -
2 1
4 3

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.0.1
PSEdition                      Core
GitCommitId                    v6.0.1
OS                             Microsoft Windows 10.0.17134
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. changed the title [-]`Select-Object` modifies input objects when using both `-ExpandProperty` and `-Property`[/-] [+]Select-Object modifies input objects when using both -ExpandProperty and -Property[/+] on Sep 12, 2018
  2. mklement0 commented on Sep 13, 2018

    @mklement0
    Contributor

    Strictly speaking, it's not the input objects that are modified, but the value of the property that -ExpandProperty targets.

    That property value can be an instance of a value type or an instance of a reference type.

    Either way, the properties specified in -Property are added as NoteProperty members to that value.

    In the case of a value-type instance, these NoteProperty members are by definition added to a copy of that instance.

    In the case of a reference-type instance, these NoteProperty members are added to the object pointed to by the reference, and any pre-existing references to that object will see the changes - in your case, that is the $NestedObject array.

    While that behavior may be surprising, it makes sense, given that there's no guaranteed way to clone reference-type instances - and implicit, automatic cloning seems to be what you're looking for (leaving aside the need to distinguish between shallow and deep cloning).

    While some reference types support cloning - and [pscustomobject] happens to be one via its .Copy() method - not all do, so the more consistent behavior is not to even attempt it.

  3. iSazonov commented on Sep 13, 2018

    @iSazonov
    Collaborator

    It would be grandiose breaking change.
    We can not even add a new switch parameter since Michael Klement (@mklement0) pointed out that there is no generic way to clone an reference object.

  4. added
    Issue-Question
    Resolution-Answered
    on Sep 13, 2018
  5. iSazonov commented on Sep 13, 2018

    @iSazonov
    Collaborator

    bstrautin

    This behavior is documented, but wrong.

    You could open a issue in PowerShell-Docs repo.

  6. bstrautin commented on Sep 13, 2018

    @bstrautin
    Author

    Cloning is not necessary; in the same way that Select-Object -Property * creates new pscustomobjects with the necessary properties, a non-surprising version of Select-Object -Property a -ExpandProperty b would create new pscustomobjects with property a and all the properties from b.

    To introduce non-modifying behavior as a non-breaking change, it seems like there are basically two options:

    1. Add a switch parameter to change the behavior of -ExpandProperty, named something like -NoModifyExpandedProperty or -ExpandPropertyAsCopy
    2. Add another parameter, named something like -CopyAndExpandProperty, which would create new pscustomobjects rather than adding note properties. It should behave more like -Property, i.e. accept multiple property names, wildcards, scriptblocks, and hashtables.
  7. mklement0 commented on Sep 13, 2018

    @mklement0
    Contributor

    Ilya (@iSazonov): I think what bstrautin meant was that the documentation is correct in that it correctly describes the current behavior, but that they consider the current behavior to be wrong.

  8. mklement0 commented on Sep 13, 2018

    @mklement0
    Contributor

    OK, so we're talking about a feature request, not a problem with the existing behavior.

    To be clear: the purpose of -ExpandProperty is to return the specified property's value as-is, optionally decorated with NoteProperty members, if -Property is also specified.

    So, yes, to get what you want, a new switch is required, but I'm unclear on the semantics:

    How would you construct the custom object if the value of the property you're targeting is an instance of a CLR runtime type such as [bool], which has no properties, or [string], which has only a Length property?
    Or do you suggest ignoring the new parameter if the value happens to be a value-type instance or a string, given that you'll implicitly get copies in that case anyway?

    What if the property value is a collection?

  9. bstrautin commented on Sep 13, 2018

    @bstrautin
    Author

    It's only a feature request if you don't consider the existing behavior to be a bug, which I do. (A Select-... cmdlet should never modify its input, but Select-Object does, semantics about "decorating" vs "modifying" aside.)

    My preference would be to change the current behavior, which would be a breaking change if anyone were actually relying on it (which seems unlikely, given how weird it is.) If that is not palatable, then it becomes a feature request.

  10. bstrautin commented on Sep 13, 2018

    @bstrautin
    Author

    How would you construct the custom object if the value of the property you're targeting is an instance of a CLR runtime type such as [bool], which has no properties, or [string], which has only a Length property?

    -ExpandPropertyAsCopy would always return objects, never scalars.

    Explanation by way of examples:

    Expanding a scalar property would return an object with that property. (The same as -Property):

    [pscustomobject] @{ one = 1; two = 2; three = 3 } | 
      Select-Object -ExpandPropertyAsCopy three

    would output

    three
    -----
        3
    

    Including -Property and expanding a scalar property would return an object with both properties. (Instead of making -Property and -ExpandProperty mutually exclusive per #6161)

    [pscustomobject] @{ one = 1; two = 2; three = 3 } | 
      Select-Object -Property one -ExpandPropertyAsCopy three

    would output

    one three
    --- -----
      1     3
    

    What if the property value is a collection?

    Basically the same as -ExpandProperty, but creating new objects instead of modifying existing ones.

    Including -Property and expanding an object property would return an object with the indicated parent and child properties, duplicating the parent properties for each child.

    [pscustomobject]@{
      a=1
      b=[pscustomobject]@{c=2; d=3}, [pscustomobject]@{c=4; d=5}
    },
    [pscustomobject]@{
      a=6
      b=[pscustomobject]@{c=7; d=8}
    } |
      Select-Object -Property a -ExpandPropertyAsCopy b

    would output

    a c d
    - - -
    1 2 3
    1 4 5
    6 7 8
    

    -ExpandPropertyAsCopy with multiple properties:

    [pscustomobject]@{
      a=1
      b=[pscustomobject]@{d=2}
      c=[pscustomobject]@{e=3}
    },
    [pscustomobject]@{
      a=4
      b=[pscustomobject]@{d=5}
      c=[pscustomobject]@{e=6}
    } |
      Select-Object -Property a -ExpandPropertyAsCopy b,c

    would produce

    a d e
    - - -
    1 2 3
    4 5 6
    

    -ExpandPropertyAsCopy with multiple list properties having would behave like LINQ's SelectMany or SQL's cross join:

    [pscustomobject]@{
      a=1
      b=[pscustomobject]@{d=2},[pscustomobject]@{d=3}
      c=[pscustomobject]@{e=4},[pscustomobject]@{e=5}
    },
    [pscustomobject]@{
      a=6
      b=[pscustomobject]@{d=7}
      c=[pscustomobject]@{e=8},[pscustomobject]@{e=9}
    } |
      Select-Object -Property a -ExpandPropertyAsCopy b,c

    would output

    a d e
    - - -
    1 2 4
    1 3 4
    1 2 5
    1 3 5
    6 7 8
    6 7 9
    

    IMO, this is how -ExpandProperty should have been designed in the first place, but that ship has sailed.

  11. mklement0 commented on Sep 13, 2018

    @mklement0
    Contributor

    It's only a feature request if you don't consider the existing behavior to be a bug, which I do.

    Let's summarize:

    • The behavior is documented.

    • The behavior is useful and opt-in: by using -ExpandProperty in combination with -Property, you're asking that NoteProperty members be added to whatever the value of the property passed to -ExpandProperty is, as documented (which is what I called decorating).

    • Nowhere does it state that "A Select-... cmdlet should never modify its input" - that may be your personal expectation and it certainly makes sense as the default behavior (which is the case), but that doesn't make the behavior in question a bug. Again: by combining -ExpandProperty with -Property you're asking for the output objects to be decorated.
      It's not a commonly used feature, but it works predictably and can be useful.

    But even if the community ends up agreeing with your assessment, backward-compatibility concerns alone would require implementing the alternative behavior envisioned by you to be opt-in.

  12. bstrautin commented on Sep 13, 2018

    @bstrautin
    Author

    Partially agree with the summary. Regardless:

    Two possible enhancements, which I am willing to develop:

    1. Change -ExpandProperty from accepting a single property name to accepting a list of property name, scriptblock, etc, like -Property. This would probably be a breaking change for consistency's sake, because expanding multiple IEnumerable properties would require creating new pscustomobjects rather than decorating the objects from a single property.
    2. Add a new parameter, -FlattenProperty or -ExpandPropertyAsCopy , which would behave as described.

    Another piece of code that demonstrates -ExpandProperty's buggy behavior, attempting to flatten two fields:

    [pscustomobject]@{
      a=1
      b=[pscustomobject]@{b2=2},[pscustomobject]@{b2=3}
      c=[pscustomobject]@{c2=4},[pscustomobject]@{c2=5}
    },
    [pscustomobject]@{
      a=6
      b=[pscustomobject]@{b2=7}
      c=[pscustomobject]@{c2=8},[pscustomobject]@{c2=9}
    } |
      Select-Object -Property a,c -ExpandProperty b |
      Select-Object -Property a,b2 -ExpandProperty c

    Expected output:

    c2 a b2
    -- - --
     4 1  2
     5 1  2
     4 1  3
     5 1  3
     8 6  7
     9 6  7
    

    Actual output, with erroneous values in b2 and errors:

    c2 a b2
    -- - --
     4 1  2
     5 1  2
    Select-Object : The property cannot be processed because the property "a" already exists.
    At line:12 char:3
    +   Select-Object -Property a,b2 -ExpandProperty c
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{b2=3; a=1; c=System.Object[]}:PSObject) [Select-Object], PSArgumentException
    + FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand
    
    Select-Object : The property cannot be processed because the property "b2" already exists.
    At line:12 char:3
    +   Select-Object -Property a,b2 -ExpandProperty c
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{b2=3; a=1; c=System.Object[]}:PSObject) [Select-Object], PSArgumentException
    + FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand
    
     4 1  2
    Select-Object : The property cannot be processed because the property "a" already exists.
    At line:12 char:3
    +   Select-Object -Property a,b2 -ExpandProperty c
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{b2=3; a=1; c=System.Object[]}:PSObject) [Select-Object], PSArgumentException
    + FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand
    
    Select-Object : The property cannot be processed because the property "b2" already exists.
    At line:12 char:3
    +   Select-Object -Property a,b2 -ExpandProperty c
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{b2=3; a=1; c=System.Object[]}:PSObject) [Select-Object], PSArgumentException
    + FullyQualifiedErrorId : AlreadyExistingUserSpecifiedPropertyExpand,Microsoft.PowerShell.Commands.SelectObjectCommand
    
     5 1  2
     8 6  7
     9 6  7
    
  13. mklement0 commented on Sep 13, 2018

    @mklement0
    Contributor

    First, let's look at how what you attempted with your sample command can be implemented with the current features:

    $NestedObjects | % { 
      $_.b.psobject.Copy() | Add-Member -PassThru -MemberType NoteProperty a -Value $_.a
    }
    • $_.b.psobject.Copy() clones the custom object that is stored in the input object's .b property
    • Add-Member -PassThru -MemberType NoteProperty a -Value $_.a adds the input object's .a property to the clone and outputs the clone.

    -ExpandPropertyAsCopy would always return objects, never scalars.

    I assume you mean it would always return (newly created) custom objects whose properties contain the requested data.

    However, that's exactly what -Property already does.

    If I understand you correctly, you're saying, with -ExpandPropertyAsCopy foo,

    • if the type of .foo is a custom object, clone it (create a new custom object with the same properties)

    • if it is a different (non-collection) type, wrap it in a custom object.

    Varying the behavior based on the type of the property passed to -ExpandPropertyAsCopy sounds ill-advised to me.

    Select-Object was not designed with special handling of custom objects as input in mind.


    -ExpandProperty by design returns a single property value from each input object.

    To me, the only logical extension of that concept to multiple properties is to return their values as individual output objects.


    Another piece of code that demonstrates -ExpandProperty's buggy behavior,

    Again, while the behavior may be surprising, it works as designed:

    You're attaching the same objects as property values to multiple objects, so modifying the attached objects via one object is reflected in the others.


    I'm personally not convinced by what you're proposing, but if you want to pursue this, I encourage you to open a new issue - or perhaps write an RFC - that explains the proposed new functionality in a focused manner.

  14. iSazonov commented on Sep 14, 2018

    @iSazonov
    Collaborator

    I must note that this cmdlet is very sensitive to changes. There is very difficult to change something without a regression.

    I believe this is ready to be concluded by PowerShell Committee
    /cc Steve Lee (@SteveL-MSFT)

  15. 28 remaining items

  16. mklement0 commented on Dec 13, 2018

    @mklement0
    Contributor

    This is already special cased depending on whether the property to expand is an object or an array.

    I wouldn't consider this special-casing, given that it's a documented feature: collection-valued properties targeted by -ExpandProperty are enumerated.

    In either case, it is the (potentially enumerated) property value itself that is currently decorated, at least from a PowerShell user's perspective.

    So, to selectively change that for [pscustomobject] instances (true "property bags") and effectively create a shallow clone of them before decorating (even if you frame it as creating a new object) amounts to special-casing.

    It's important to understand that for other types the -ExpandProperty value itself is modified, and that can't be changed:

    # Expand a [System.IO.DirectoryInfo] property value:
    $obj = [pscustomobject] @{ foo = 'hi'; bar = Get-Item / }
    ($obj | Select-Object -ExpandProperty bar -Property foo).foo  # -> 'hi'
    $obj.bar.foo # -> 'hi' - enclosing $obj sees the change too

    Now, perhaps the predominant use case for the - itself not all-too common - combination of -ExpandProperty and -Property is with [pscustomobject] instances with the expectation of creating new objects always, so, yes, analyzing current usage is needed.

    If so, then the quiet special-casing of [pscustomobject] will indeed make things easier, but, as stated, the special-casing would have to be carefully documented so that users won't be surprised if non-custom objects are directly "modified" (decorated).


    bstrautin: Yes, if you want to retain all iterations of a custom object, iterative modification of the same object is not an option, but I was thinking more of a "working object" scenario: a reusable object whose temporary state is captured by transformation to a different object / format.

    My sense is that repeated Select-Object -ExpandProperty -Property calls on the same object should not fail, and simply update existing properties, but that's a separate issue.

    However, implementing the latter would - from the perspective of your new-object expectation - make the behavior potentially more obscure; if we opt for quiet special-casing, that point would be moot.

  17. SteveL-MSFT commented on Jan 30, 2019

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee reviewed this. We believe the original intent is to not modify the original object and this looks like a bug. This is a Breaking Change, but the benefit outweighs the potential impact. We agree that we should just fix the original behavior so that a new object is emitted.

  18. added
    Breaking-Change
    Committee-Reviewed
    Up-for-Grabs
    and removed
    Review - Committee
    on Jan 30, 2019
  19. iSazonov commented on Jan 31, 2019

    @iSazonov
    Collaborator

    I'd postpone the change till next PowerSHell Core LTS version.

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

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

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

  23. added
    Resolution-No Activity
    on Nov 16, 2023
  24. 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

    Breaking-ChangeCommittee-ReviewedIssue-QuestionResolution-No ActivityUp-for-Grabs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions