Skip to content

PSCustomObject still has properties like Count and ForEach, even in strict mode #15526

Closed

Description

@binyomen

Steps to reproduce

Set-StrictMode -Version Latest

$object = [PSCustomObject]@{A=1; B=2; C=3; D=4; E=5}
$object.Count # does not throw after version 6.1

More thorough repros/differences by version

Expected behavior

The error text below when trying to access the Count property.

The property 'Count' cannot be found on this object. Verify that the property exists.

Actual behavior

The Count property returns the value of 1.

1

Environment data

Name                           Value
----                           -----
PSVersion                      7.1.3
PSEdition                      Core
GitCommitId                    7.1.3
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

More detail

Basically, one of the features of the latest version of strict mode is that trying to access non-existent properties on an object results in an exception. This includes properties like Count, which are available on all objects outside of strict mode.

However, after #3671 was resolved, PSCustomObject no longer throws when you try to access Count in strict mode. The same is true for Length. This differs from the behavior of other objects such as numbers, strings, and process objects, which throw when Count is accessed.

If we want to follow #2798, then potentially the other objects like numbers should have their behavior changed. But as it stands, it seems like PSCustomObject is special in that it doesn't match the behavior of other types in strict mode.

Activity

  1. added
    Needs-Triage
    on Jun 5, 2021
  2. 237dmitry commented on Jun 5, 2021

    @237dmitry

    This differs from the behavior of other objects such as numbers, strings, and process objects, which throw when Count is accessed.

    They do not throw:

    ss

  3. binyomen commented on Jun 5, 2021

    @binyomen
    Author

    Sorry if I didn't clarify enough in the issue description. In your example, I wouldn't expect any of those to throw in strict mode either. PSCustomObject doesn't throw, and that's the subject of this issue. Strings won't throw when accessing Length, since that's a valid property on strings. They will throw when accessing Count, though. (gps).Count doesn't throw, since gps returns an array, and arrays have a Count property.

    My reasoning behind creating the issue is that most objects that don't have Count (or Length) properties throw in strict mode when you try to access those properties. PSCustomObject doesn't throw, however, which seems like inconsistent behavior.

    Does that make sense?

    PS>Set-StrictMode -Version Latest
    PS>'aaa'.Count
    PropertyNotFoundException: The property 'Count' cannot be found on this object. Verify that the property exists.
    PS>(gps)[0].Count
    PropertyNotFoundException: The property 'Count' cannot be found on this object. Verify that the property exists.
    PS>(4).Count
    PropertyNotFoundException: The property 'Count' cannot be found on this object. Verify that the property exists.
    PS>
  4. jborean93 commented on Jun 5, 2021

    @jborean93
    Collaborator

    (gps).Count doesn't throw, since gps returns an array, and arrays have a Count property.

    I don't think that is true, Array does not have a Count property, they just have Length so this is another edge case where Count is present. I don't really have any strong feelings either way though, Strict Mode is mostly a curiosity for me and not something I've used successfully in the past.

  5. binyomen commented on Jun 5, 2021

    @binyomen
    Author

    From using Get-Member, it seems like arrays have both a Count and a Length property, although I might be missing something:

    PS> Get-Member -InputObject @(1, 2, 3)
    
       TypeName: System.Object[]
    
    Name           MemberType            Definition
    ----           ----------            ----------
    Add            Method                int IList.Add(System.Object value)
    Address        Method                System.Object&, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicK…
    Clear          Method                void IList.Clear()
    Clone          Method                System.Object Clone(), System.Object ICloneable.Clone()
    CompareTo      Method                int IStructuralComparable.CompareTo(System.Object other, System.Collections.IComp…
    Contains       Method                bool IList.Contains(System.Object value)
    CopyTo         Method                void CopyTo(array array, int index), void CopyTo(array array, long index), void I…
    Equals         Method                bool Equals(System.Object obj), bool IStructuralEquatable.Equals(System.Object ot…
    Get            Method                System.Object Get(int )
    GetEnumerator  Method                System.Collections.IEnumerator GetEnumerator(), System.Collections.IEnumerator IE…
    GetHashCode    Method                int GetHashCode(), int IStructuralEquatable.GetHashCode(System.Collections.IEqual…
    GetLength      Method                int GetLength(int dimension)
    GetLongLength  Method                long GetLongLength(int dimension)
    GetLowerBound  Method                int GetLowerBound(int dimension)
    GetType        Method                type GetType()
    GetUpperBound  Method                int GetUpperBound(int dimension)
    GetValue       Method                System.Object GetValue(Params int[] indices), System.Object GetValue(int index), …
    IndexOf        Method                int IList.IndexOf(System.Object value)
    Initialize     Method                void Initialize()
    Insert         Method                void IList.Insert(int index, System.Object value)
    Remove         Method                void IList.Remove(System.Object value)
    RemoveAt       Method                void IList.RemoveAt(int index)
    Set            Method                void Set(int , System.Object )
    SetValue       Method                void SetValue(System.Object value, int index), void SetValue(System.Object value,…
    ToString       Method                string ToString()
    Item           ParameterizedProperty System.Object IList.Item(int index) {get;set;}
    Count          Property              int Count {get;}
    IsFixedSize    Property              bool IsFixedSize {get;}
    IsReadOnly     Property              bool IsReadOnly {get;}
    IsSynchronized Property              bool IsSynchronized {get;}
    Length         Property              int Length {get;}
    LongLength     Property              long LongLength {get;}
    Rank           Property              int Rank {get;}
    SyncRoot       Property              System.Object SyncRoot {get;}
    

    However, PSCustomObject doesn't have a Count property:

    PS> Get-Member -InputObject ([pscustomobject]@{a=1; b=2})
    
       TypeName: System.Management.Automation.PSCustomObject
    
    Name        MemberType   Definition
    ----        ----------   ----------
    Equals      Method       bool Equals(System.Object obj)
    GetHashCode Method       int GetHashCode()
    GetType     Method       type GetType()
    ToString    Method       string ToString()
    a           NoteProperty int a=1
    b           NoteProperty int b=2
    

    Neither do strings or numbers (Int32 in this case):

    PS> Get-Member -InputObject 'aaa'
    
       TypeName: System.String
    
    Name                 MemberType            Definition
    ----                 ----------            ----------
    Clone                Method                System.Object Clone(), System.Object ICloneable.Clone()
    CompareTo            Method                int CompareTo(System.Object value), int CompareTo(string strB), int ICompar…
    Contains             Method                bool Contains(string value), bool Contains(string value, System.StringCompa…
    CopyTo               Method                void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int …
    EndsWith             Method                bool EndsWith(string value), bool EndsWith(string value, System.StringCompa…
    EnumerateRunes       Method                System.Text.StringRuneEnumerator EnumerateRunes()
    Equals               Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(stri…
    GetEnumerator        Method                System.CharEnumerator GetEnumerator(), System.Collections.IEnumerator IEnum…
    GetHashCode          Method                int GetHashCode(), int GetHashCode(System.StringComparison comparisonType)
    GetPinnableReference Method                System.Char&, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, Pub…
    GetType              Method                type GetType()
    GetTypeCode          Method                System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()
    IndexOf              Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int Index…
    IndexOfAny           Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex),…
    Insert               Method                string Insert(int startIndex, string value)
    IsNormalized         Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normal…
    LastIndexOf          Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), i…
    LastIndexOfAny       Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int star…
    Normalize            Method                string Normalize(), string Normalize(System.Text.NormalizationForm normaliz…
    PadLeft              Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char padding…
    PadRight             Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char paddi…
    Remove               Method                string Remove(int startIndex, int count), string Remove(int startIndex)
    Replace              Method                string Replace(string oldValue, string newValue, bool ignoreCase, culturein…
    Split                Method                string[] Split(char separator, System.StringSplitOptions options), string[]…
    StartsWith           Method                bool StartsWith(string value), bool StartsWith(string value, System.StringC…
    Substring            Method                string Substring(int startIndex), string Substring(int startIndex, int leng…
    ToBoolean            Method                bool IConvertible.ToBoolean(System.IFormatProvider provider)
    ToByte               Method                byte IConvertible.ToByte(System.IFormatProvider provider)
    ToChar               Method                char IConvertible.ToChar(System.IFormatProvider provider)
    ToCharArray          Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
    ToDateTime           Method                datetime IConvertible.ToDateTime(System.IFormatProvider provider)
    ToDecimal            Method                decimal IConvertible.ToDecimal(System.IFormatProvider provider)
    ToDouble             Method                double IConvertible.ToDouble(System.IFormatProvider provider)
    ToInt16              Method                short IConvertible.ToInt16(System.IFormatProvider provider)
    ToInt32              Method                int IConvertible.ToInt32(System.IFormatProvider provider)
    ToInt64              Method                long IConvertible.ToInt64(System.IFormatProvider provider)
    ToLower              Method                string ToLower(), string ToLower(cultureinfo culture)
    ToLowerInvariant     Method                string ToLowerInvariant()
    ToSByte              Method                sbyte IConvertible.ToSByte(System.IFormatProvider provider)
    ToSingle             Method                float IConvertible.ToSingle(System.IFormatProvider provider)
    ToString             Method                string ToString(), string ToString(System.IFormatProvider provider), string…
    ToType               Method                System.Object IConvertible.ToType(type conversionType, System.IFormatProvid…
    ToUInt16             Method                ushort IConvertible.ToUInt16(System.IFormatProvider provider)
    ToUInt32             Method                uint IConvertible.ToUInt32(System.IFormatProvider provider)
    ToUInt64             Method                ulong IConvertible.ToUInt64(System.IFormatProvider provider)
    ToUpper              Method                string ToUpper(), string ToUpper(cultureinfo culture)
    ToUpperInvariant     Method                string ToUpperInvariant()
    Trim                 Method                string Trim(), string Trim(char trimChar), string Trim(Params char[] trimCh…
    TrimEnd              Method                string TrimEnd(), string TrimEnd(char trimChar), string TrimEnd(Params char…
    TrimStart            Method                string TrimStart(), string TrimStart(char trimChar), string TrimStart(Param…
    Chars                ParameterizedProperty char Chars(int index) {get;}
    Length               Property              int Length {get;}
    
    PS> Get-Member -InputObject 5
    
       TypeName: System.Int32
    
    Name        MemberType Definition
    ----        ---------- ----------
    CompareTo   Method     int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.…
    Equals      Method     bool Equals(System.Object obj), bool Equals(int obj), bool IEquatable[int].Equals(int other)
    GetHashCode Method     int GetHashCode()
    GetType     Method     type GetType()
    GetTypeCode Method     System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()
    ToBoolean   Method     bool IConvertible.ToBoolean(System.IFormatProvider provider)
    ToByte      Method     byte IConvertible.ToByte(System.IFormatProvider provider)
    ToChar      Method     char IConvertible.ToChar(System.IFormatProvider provider)
    ToDateTime  Method     datetime IConvertible.ToDateTime(System.IFormatProvider provider)
    ToDecimal   Method     decimal IConvertible.ToDecimal(System.IFormatProvider provider)
    ToDouble    Method     double IConvertible.ToDouble(System.IFormatProvider provider)
    ToInt16     Method     short IConvertible.ToInt16(System.IFormatProvider provider)
    ToInt32     Method     int IConvertible.ToInt32(System.IFormatProvider provider)
    ToInt64     Method     long IConvertible.ToInt64(System.IFormatProvider provider)
    ToSByte     Method     sbyte IConvertible.ToSByte(System.IFormatProvider provider)
    ToSingle    Method     float IConvertible.ToSingle(System.IFormatProvider provider)
    ToString    Method     string ToString(), string ToString(string format), string ToString(System.IFormatProvider provi…
    ToType      Method     System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)
    ToUInt16    Method     ushort IConvertible.ToUInt16(System.IFormatProvider provider)
    ToUInt32    Method     uint IConvertible.ToUInt32(System.IFormatProvider provider)
    ToUInt64    Method     ulong IConvertible.ToUInt64(System.IFormatProvider provider)
    TryFormat   Method     bool TryFormat(System.Span[char] destination, [ref] int charsWritten, System.ReadOnlySpan[char]…
    
  6. 237dmitry commented on Jun 5, 2021

    @237dmitry

    it seems like arrays have both a Count and a Length property

    I think this was left for backward compatibility with Windows Powershell, where Count was an alias for Length and very many scripts use both of them.

  7. jborean93 commented on Jun 5, 2021

    @jborean93
    Collaborator

    It’s not documented in the Array type. While it appears as an adapted property it’s still not part of the underlying type AFAIK.

  8. binyomen commented on Jun 5, 2021

    @binyomen
    Author

    It’s not documented in the Array type. While it appears as an adapted property it’s still not part of the underlying type AFAIK.

    It looks like it is documented there. Under "Explicit Interface Implementations" the page lists ICollection.Count.

  9. vexx32 commented on Jun 6, 2021

    @vexx32
    Collaborator

    Count tends to persist on most PS objects because it is an automatic property. If you check the Count property of any non-array it will generally give you the result 1, except if the value you're checking is $null, when it may be 0.

    This is so that users don't have to be hypervigilant over whether a given pipeline result is one or multiple items, and can simply check Count.

    Not sure how consistently it works in strict mode, though.

  10. mklement0 commented on Jul 20, 2021

    @mklement0
    Contributor

    Engine-supplied members such as .Count, .Length, .psobject, ForEach(), .... now have an official name: intrinsic members.

    It makes much more sense to make them consistently available irrespective of strict mode.

    This is already true for most of them, but inexplicably not for .Count and .Length (in general), despite their tremendous usefulness in unified handling of scalars and collections, as mentioned by Rain Sallow (/u/ta11ow) (@vexx32).

    In short: Fix #2798, and everyone will live happily ever after.

    Set-StrictMode isn't heavily used anyway, but at least for me it was #2798 that prevented me from ever using Set-StrictMode -Version 2 or higher.

    Here's a quick demonstration of the inconsistency:

    # .psobject, .ForEach(), scalar indexing already work in all strict modes, .Count does not.
    PS> & { Set-StrictMode -version Latest; ('foo').psobject; ('foo').ForEach({"[$_]"}); (42)[0]; ('foo').Count }
    
    
    BaseObject          : foo
    Members             : {char Chars(int index) {get;}, int Length {get;}, Remove, Replace…}
    Properties          : {int Length {get;}}
    Methods             : {Remove, Replace, Split, Substring…}
    ImmediateBaseObject : foo
    TypeNames           : {System.String, System.Object}
    
    [foo]
    42
    
    PropertyNotFoundException: The property 'Count' cannot be found on this object. Verify that the property exists.
  11. 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.

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

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

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

    Needs-TriageResolution-No ActivityWG-Engine-ParameterBinder

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions