Skip to content

Hidden-only class loses ToString() formatting after Get-Member inspection #25832

Open

Description

@GregoireLD

Prerequisites

Steps to reproduce

If you define a class with only hidden properties and an overload to the ToString() method, displaying the object falls back to the ToString() method, as expected.

But a call to Get-Member on such an object, forces a full ETS refresh: the formatter now believes the type has visible members and switches to the list renderer, resulting in blank lines (since actually all members are hidden) instead of the expected ToString().

I found this issue was first noticed in issue #17071 but I just ran into it myself when coding a new class in PowerShell. It's still occurring on PowerShell 7.5.2 .

Code snippet

1. Minimalistic sample class

class CustomClass {
    hidden [string] $myString
    CustomClass([string] $newVal) { $this.myString = $newVal }
    [string] ToString() { return $this.myString }
}

$myObject = [CustomClass]"Test"

# 1. Normal display uses ToString()
$myObject

# 2. Inspect the object
$myObject | Get-Member

# 3. Display again – blank line appears
$myObject

Expected behavior

PS /> $myObject = [CustomClass]"Test"
PS /> $myObject
Test
PS /> $myObject | Get-Member

   TypeName: CustomClass

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

PS /> $myObject
Test

Actual behavior

PS /> $myObject = [CustomClass]"Test"
PS /> $myObject
Test
PS /> $myObject | Get-Member

   TypeName: CustomClass

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()

PS /> $myObject

Error details

Environment data

PS /> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.5.2
PSEdition                      Core
GitCommitId                    7.5.2
OS                             Darwin 24.6.0 Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:29 PDT 2025; root:xnu-11417.…
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Aug 6, 2025
  2. similar-issues-ai commented on Aug 6, 2025

    @similar-issues-ai

    We've found some similar issues:

    If any of the above are duplicates, please consider closing this issue out and adding additional context in the original issue.

    Note: You can give me feedback by 👍 or 👎 this comment.

  3. GregoireLD commented on Aug 8, 2025

    @GregoireLD
    Author

    I might be completely wrong, and I can't currently perform much compiling, but after staring the code a lot, I think I might've found the culprit.

    if (DefaultScalarTypes.IsTypeInList(typeNames)
    || !HasNonRemotingProperties(so))
    {
    // we force a ToString() on well known types
    return GenerateOutOfBandObjectAsToString(so);
    }

    Here we treat the object as a scalar but only if either, it's a standard type (Which my object is never, so always false in my case) or, if HasNonRemotingProperties is false.

    I think before the introspection it's indeed false, but after the ETS checks on all hidden properties, it must switch to true, skip the scalar treatment, and reach the empty list or table treatment bellow.

    I'm not sure about modifying the HasNonRemotingProperties itself, but maybe having no visible property could be a third valid reason to get the scalar treatment. I don't feel fluent enough in C# to tackle this myself, but I hope this helps.

  4. mklement0 commented on Aug 10, 2025

    @mklement0
    Contributor

    GregoireLD, I haven't looked too deeply, but I don't think this is where the problem lies:

    • DefaultScalarTypes.IsTypeInList's behavior is static, and would never return true for you custom class

    • While it's not readily obvious whether HasNonRemotingProperties takes hidden properties into account, note that the problem also surfaces with property-less types, for which it should return false either way.

    A simple repro:

    class Foo { [string] ToString() { return 'hi' } }; ($o = [Foo]::new()); $null = $o | Get-Member; $o; '(done)'

    Interestingly, piping to Format-List -Force surfaces the bug, too.

  5. GregoireLD commented on Aug 12, 2025

    @GregoireLD
    Author

    Michael Klement (@mklement0) indeed I agree

    • DefaultScalarTypes.IsTypeInList's behavior is static, and would never return true for you custom class

    Yeah that's my understanding too

    • While it's not readily obvious whether HasNonRemotingProperties takes hidden properties into account, note that the problem also surfaces with property-less types, for which it should return false either way.

    Interesting, but I'm wondering if property-less types in that context could still get technical properties attached from calling commands like Get-Member.

    My line of thought is that I can't find any other places where the output don't get wrapped in new-lines :
    My custom type is outputting a single string from the ToString method.

    • At first, before triggering the bug, the line is written "raw" with no extra lines.
    • After triggering the bug, it gets wrapped in extra lines no matter what.

    that's why I was searching for a place that would fit this: depending on this single "if" statement, we split between a GenerateOutOfBandObjectAsToString(so) with no extra lines, or the usual object output with wrapping lines. This would also match why forcing a "Format-List -Force" also triggers the bug as you noted.

    My other side-note though is, since property-less types are bound to output using (theirs or inherited) ToString() method, letting them go through the same path as simple strings could make sense (which seems to be the default, pre-bug behavior anyway) -> adding a third condition in this if statement: 1. DefaultScalarTypes, or 2. no HasNonRemotingProperties, or 3. property-less object .

    As stated before, I'm still pretty new to the PowerShell code-base so I might be completely off-track tho.

  6. GregoireLD commented on Aug 12, 2025

    @GregoireLD
    Author

    I can confirm this is where it happens: (I know my probing was a bit ... brutal)

    when replacing line 510 of FormatViewManager.cs with

    GenerateOutOfBandObjectAsToString("Test");
    

    any subsequent call to my object display "Test" as a Scalar (with no extra lines), and after triggering the bug, it's back to my usual displaying of empty lines. So yes I'm pretty sure this is where it happens.

    One extra issue that possibly lies in here too, If I specify a "format.ps1xml" file to my class:

    • first, it will be ignored until I run "Get-Member" ;
    • and secondly, I can't seem to find a way to make a format.ps1xml output a Scalar anyway.
  7. mklement0 commented on Aug 12, 2025

    @mklement0
    Contributor

    Thanks for digging deeper.

    So the implication seems to be that the return value of !HasNonRemotingProperties(so) changes after having called Get-Member or Format-List -Force - for reasons unknown to me, given that piping to Get-Member -Force doesn't reveal any (unexpectedly) attached new properties.

    Note that the method name HasNonRemotingProperties() implies that it should also return false for property-less instances, so there should be no need to amend the conditional.

    In the context of for-display formatting, the semantics of HasNonRemotingProperties() should really be HasNonHiddenNonRemotingProperties(), but I haven't dug deep enough to verify that hidden properties are excluded.

  8. GregoireLD commented on Aug 12, 2025

    @GregoireLD
    Author

    I'm slowly inching my way towards understanding this ... the split is not exactly where I initially thought.

    The split appears to occurs on line 510 indeed, but if it doesn't branch here, it doesn't go all the way to the end of the method, it's caught right bellow with the if (!useToStringFallback), immediately returning null

    I'm currently testing what would be the consequences of flipping the useToStringFallback flag here

  9. GregoireLD commented on Aug 12, 2025

    @GregoireLD
    Author

    Unfortunately switching the useToStringFallback flag messes with other outputs.

    Yet, I have found the following minimal changes to fix the current behavior with no visible downsides so far:

    • In FormatViewManager.cs:
      • relocate the property test from lines 518/522 into the if at line 507/509
      • if we have no visible properties -> we fallback to a ToString call (similar to the current pre-bug behavior)
        • add || (new PSPropertyExpression("*").ResolveNames(so).Count == 0) to the current if check at line 508/509
        • removing the now relocated new PSPropertyExpression("*").ResolveNames(so)... == 0 check at lines 518/522

    This:

    • perform the test before the useToStringFallback, because this one will trigger a return null anyway
    • return the ToString() content of the object instead of null if the object has no visible properties

    At first glance, It could be said this introduce a behavior change since we return a ToString without checking the useToStringFallback flag, but currently it's the other way around : after the bug gets triggered, the code will return null instead of the ToString only when we allow for a useToStringFallback (and before the bug, we get a ToString anyway too).

    Added "Bonus" of some kind, Format-List -Force stays the same before and after triggering, and is empty, similarly to other raw Scalars we can encounter (42 | Format-List -Force is empty too) but does not induce any output issue anymore.

    So far I haven't run into any issues after making these changes, but I'd like to have someone more experienced to run some tests too before I even think of making a PR about it 😊

  10. GregoireLD commented on Aug 12, 2025

    @GregoireLD
    Author

    I noticed one thing this change makes (but I think it's a good thing), if you have a format.ps1xml associated with your class:

    currently:

    • For a property-less class, the xml gets ignored until you make a call to Get-Member or anything that would trigger the bug on each object of said class. behavior is heavily object-dependent.
    • For a property-equipped class, the xml is used right away, behavior is constant.

    after this fix:

    • For a property-less class, the xml is never used, object is treated as a scalar, behavior is constant.
    • For a property-equipped class, the xml is always used, behavior is constant.

    I was perplexed as to how I could use the format.ps1xml file to specify a simple scalar output, and it seems there is no way to do that. This fix offers a direct solution, any property-less object is by default treated as a scalar, and the format.ps1xml is used automatically on any property-equipped object.

  11. GregoireLD commented on Aug 13, 2025

    @GregoireLD
    Author

    Here is the consolidated changes I'm suggesting :
    GregoireLD:PowerShell-PropertylessFix

  12. GregoireLD commented on Aug 13, 2025

    @GregoireLD
    Author

    To double-check my idea, I tracked when was the change to HasNonRemotingProperties() made.
    I discovered that prior to this change, on Commit 42c289f, the test was indeed against the now defunct IsPropertyLessObject(so) but was changed apparently for performance reasons.

    Commit 42c289f Compare

    As such, I feel more and more confident about my change, given that performance-wise, the lazy evaluation means that:

    • if HasNonRemotingProperties() is true it won't go any further, and
    • if not, the (new PSPropertyExpression("*").ResolveNames(so).Count == 0) then gets evaluated here, restoring the original aim of making sure property-less objects returns their ToString() content and not a null value.
  13. mklement0 commented on Aug 13, 2025

    @mklement0
    Contributor

    I haven't dug deeper, but I'm thinking a fix would require two things:

    • Make HasNonRemotingProperties() invariably exclude hidden properties or, if it is used elsewhere where hidden properties should be reported, make it accept a MshMemberMatchOptions argument and pass None - there should then be no need for (new PSPropertyExpression("*").ResolveNames(so).Count == 0)

    • Fix the fact that Get-Member and Format-List -Force change the behavior of existing instances.

    I've checked the Windows PowerShell behavior, and it is correct for both property-less and hidden-properties-only types.

    Perhaps Staffan Gustafsson (@powercode), who authored the PR that may have introduced the bug, can share his thoughts.

  14. GregoireLD commented on Aug 14, 2025

    @GregoireLD
    Author

    If I understand correctly, current HasNonRemotingProperties() is a lambda-expression that relies on the FirstOrDefault(predicate) function, predicate being the filtered name tests in IsNotRemotingProperty(string name)

    I don't see how to make a filter like FirstOrDefault become FirstVisibleOrDefault without rebuilding it from scratch (but I'm a C# newbie so maybe that's on me).

    Prior to this change, the check we are talking about was referring to the following function:

    internal static bool IsPropertyLessObject(PSObject so)
            {
                List<MshResolvedExpressionParameterAssociation> allProperties = AssociationManager.ExpandAll(so);
    
                if (allProperties.Count == 0)
                {
                    return true;
                }
    
                if (allProperties.Count == 3)
                {
                    foreach (MshResolvedExpressionParameterAssociation property in allProperties)
                    {
                        if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase))
                        {
                            return false;
                        }
                    }
    
                    return true;
                }
    
                if (allProperties.Count == 4)
                {
                    foreach (MshResolvedExpressionParameterAssociation property in allProperties)
                    {
                        if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase)
                            && !property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase))
                        {
                            return false;
                        }
                    }
    
                    return true;
                }
    
                if (allProperties.Count == 5)
                {
                    foreach (MshResolvedExpressionParameterAssociation property in allProperties)
                    {
                        if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase) &&
                            !property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceLength, StringComparison.OrdinalIgnoreCase))
                        {
                            return false;
                        }
                    }
    
                    return true;
                }
    
                return false;
            }

    I which we see the end part is all that subsist nowadays in the form of the current HasNonRemotingProperties() function.

    If I understand correctly, the old test was retrieving all properties (supposedly visible), and excluding RemotingProperties from the count to get a final visibility check.

    One (easy, in the sense I think I could do it) way could be to replace this current call to HasNonRemotingProperties() in the "if" with a modernized IsPropertyLessObject(PSObject so), checking both for the HasNonRemotingProperties() and counting visible properties returning a directly usable single boolean value.

  15. GregoireLD commented on Aug 14, 2025

    @GregoireLD
    Author

    Here is my findings so far:

    • Restoring the IsPropertyLessObject(PSObject so) "as-is" (minus the no-longer-existing SourceLength RemotingConstant) fixes the issue, restore the initial behavior, fully matching what is expected, and what we see on Windows PowerShell
    • I noticed there was a new RemotingConstant in the RemotingConstants class : EventObject ; I added it to the current IsNotRemotingProperty method
    • I rebuilt a new, simpler, IsPropertyLessObject(PSObject so), leveraging the current IsNotRemotingProperty method

    Proposed modification

  16. mklement0 commented on Aug 15, 2025

    @mklement0
    Contributor

    Thanks for all your efforts, GregoireLD

    It still seems to me that two aspects need to be expressed explicitly:

    • ensuring that only non-hidden among the (non-remoting) properties are considered
    • investigating how calls to Get-Member / Format-List -Force unexpectedly change the current behavior, and whether other use cases may be affected too.

    Once we have clarity and agreement on how to proceed, a PR can be created.

  17. GregoireLD commented on Aug 15, 2025

    @GregoireLD
    Author

    Michael Klement (@mklement0) true, I've build a few more sets to tests this but as far as I understand:

    • the AssociationManager.ExpandAll(so) / allProperties.Count I currently use in my new IsPropertyLessObject(PSObject so) function does not get fooled by hidden properties and only return true is there is valid visible non-remote properties in said object.
    • In the end, the issue seems not to be caused by Get-Member and such, but in the way the Lambda HasNonRemotingProperties(so) is parsing the object :
      • When introspecting the case were properties were mistakenly reported as existing, I found HasNonRemotingProperties(so) apparently saw the static "PSTypeNames" class member and mistakenly confronted it to the Non-Remoting list. My understanding is that the way this lambda evaluates the object was too wide and encompasses more than just properties belonging to the object, but also "wrapping" or additional "tooling" properties, causing issues once the object gets populated with non-properties class members -> That explains why calling IsNotRemotingProperty(property) explicitly solely on each visible properties solves it, it doesn't wrongly mistakes non-property class members as valid properties.
    • HasNonRemotingProperties(so) is only used at one other location, and in the exact same context of filtering PropertyLessObject : OutGridViewCommand.cs, which displays the same issue. I just replaced it in the exact same way for consistency and I'm currently rebuilding this new version to test it.

    Let me know if this shed some more light on all of this

    Current test

  18. mklement0 commented on Aug 15, 2025

    @mklement0
    Contributor

    That sounds promising, but I still don't understand why the symptom only surfaces after having called Get-Member or Format-List -Force.

  19. GregoireLD commented on Aug 15, 2025

    @GregoireLD
    Author

    This is what I will try to understand next, but for what it's worth, I indeed saw that .pstypenames is a hidden "CodeProperty" member that does exist from the get go (That's the one I saw appear when inspecting the former HasNonRemotingProperties() method).

    So I get the feeling it's a combination of caching the existence of a hidden property, and going through a HasNonRemotingProperties() non-visibility aware that wrongly returns that some properties must be visible.

    I will see if I find any wrongdoing on the Get-Member side, but the fact that the object-side fixes it might indicate the issue was only there.

  20. GregoireLD commented on Aug 16, 2025

    @GregoireLD
    Author

    I'm pulling at straws here as things are getting a bit hard to follow for a newcomer like me, but I think I got the big picture :

    • At first the object is built without triggering anything on the ETS side, everything is working fine
    • when calling Get-Member, a series of call ends up calling PSObject.GetMemberCollection
      • the TableView and FormatViewManager have an indirect path through ExpandAll(so) but ends up in the same place
    • the GetMemberCollection function triggers a set of delegates for the Extended / Adapted / Base views
    • then PSMemberInfoInternalCollection<T> ret = msjObj.InternalAdapter.BaseGetMembers<T>(msjObj._immediateBaseObject); reflects / adapts the object and returns all properties, including hidden ones, but here it's fine I think. and PSMemberInfoIntegratingCollection collates all newly discovered properties.
    • Once these ETS properties gets attached to the object, the reflected / adapted properties are part enough of the object to be analyzed by the current HasNonRemotingProperties(so), triggering the issue.

    As far as I understand, everything else is fine here, just that the object itself "knows" which properties it owns and which are visibles, and relying solely on the HasNonRemotingProperties(so) delegate included reflected properties that should never be included here in the first place.

    I think no changes are required elsewhere, just in the FormatViewManager (and the same change in OutGridViewCommand)

  21. GregoireLD commented on Aug 16, 2025

    @GregoireLD
    Author

    Michael Klement (@mklement0) Do you think this could be ready to propose as a PR for closer inspection ?

    Current Status

  22. mklement0 commented on Aug 16, 2025

    @mklement0
    Contributor

    I'd say so, yes.

    One aspect left to address is that the original PR's motivation was a performance improvement, so it would be good to understand the performance impact of your proposed fix.

    A fix is undoubtedly necessary, but perhaps there is a way to improve its performance through caching - I personally cannot speak to that (I don't know the cost of repeated AssociationManager.ExpandAll(so) calls).

    Again, thanks for your efforts.

  23. GregoireLD commented on Aug 16, 2025

    @GregoireLD
    Author

    True.
    What I hope is that, this since this will only impact objects without associated views, or propertyless objects when called without an explicit ToString() invocation, the impact should be fairly limited. And the optimisation scope of the previous PR was fairly large, this will only undermine one of the many optimisations.

    PR Done, thanks for all your help Michael Klement (@mklement0) , I'm pretty new to this 😊

    I don't know the process from here (not that I knew much before here either 😅), feel free to let me know if I should do anything else

  24. added
    WG-NeedsReview
    WG-Engine
    on Sep 11, 2025
  25. GregoireLD commented on Sep 18, 2025

    @GregoireLD
    Author

    Just to link this to the PR to this issue :
    PR 25871

    As I'm not yet accustomed to this repo's procedures, feel free to notify me if anything is needed from me.

  26. iSazonov commented on Nov 22, 2025

    @iSazonov
    Collaborator

    So the implication seems to be that the return value of !HasNonRemotingProperties(so) changes after having called Get-Member or Format-List -Force - for reasons unknown to me, given that piping to Get-Member -Force doesn't reveal any (unexpectedly) attached new properties.

    Michael Klement (@mklement0) I guess Engine does "full psobject init" and as result add pstypenames property.

  27. powercode commented on Apr 6, 2026

    @powercode
    Collaborator

    Unfortunately, I cannot help you with any insights. I took me a while to even remember that I had made that PR.

    As I recall, the focus was to not allocate as many objects for formatting and optimize how PSObject allocated when we knew up front how many properties it would have.

    I would suspect that the focus of both the implementation and the review was centered around those changes, and that edge cases weren't properly considered.

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-TriageWG-EngineWG-NeedsReview

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions