Repository navigation
Description
Summary of the new feature/enhancement
A developer might have created some custom type that aims to behave like a primitive or built-in type, but PowerShell does not provide a way to let the developer precisely control formatting of custom types. In particular, the handling of string is very special --- it implements IEnumerable<char>, but will not be enumerated (into a stream of chars) when formatted. There is no way for a custom type to be handled like a string.
Another example. Currently, System.Text.Rune does not have special handling, and the default formatting is Format-List instead of ToString(). Arguably, ToString() is more appropriate. For a custom type, the only way to force ToString() formatting is to apply System.Management.Automation.HiddenAttribute to all instance fields and properties. However, this comes with the downside of referencing PowerShell in the assembly containing the type, but the assembly should be usable even in an environment without PowerShell (and you don't want to load PowerShell assemblies if you aren't using it anyway).
The closest we can get for Rune (or any other custom type not implementing IEnumerable nor IEnumerator) is to give it a Custom view, but it will add blank lines when outputting. Not ideal...
This issue aims to generate discussion on creating mechanisms to have fine-grained control over (default) formatting of a type. Related #9538.
Proposed technical implementation details (optional)
Here is a simple proposal.
- Decouple
Out-DefaultintoFormat-DefaultandOut-Host. Today's PowerShell handlesOut-Defaultmonolithically. It choosesFormat-TableorFormat-ListorToString()-formatting, depending on the number of non-hidden public fields and properties, and then appliesOut-Host. - In
Format.ps1xml, allow a new type ofNativeControl. It specifies a type name, which, if found in loaded assemblies, is used to format the object. Format-Defaultchooses the format as follows:- If there is a view defined for this type, use the first available view (which does not have to be
NativeControlview). However, ifNativeControlformatter was used to produce the object being formatted (formatting is recursive forNativeControlviews), thenNativeControlis skipped. - Otherwise, use today's default formatting choice. (Special handling for
string; useToString()if there is no non-hidden public fields or properties; useFormat-Tableif there are only a few; useFormat-Listif there are many.)
- If there is a view defined for this type, use the first available view (which does not have to be
Make the types in Microsoft.PowerShell.Commands.Internal.Format public, so people can create custom format objects. Provide a new abstract class:
// or another namespace?
namespace System.Management.Automation
{
// The derived class must be stateless, so that
// only one instance is created per PowerShell runspace.
public abstract class NativeFormatter
{
// The returned object is recursively formatted,
// but cannot be sent to the same formatter again.
public abstract object FormatObject(object obj);
}
}For example, suppose we have a custom string class AsciiString, then we can create
public sealed class AsciiStringFormatter : NativeFormatter
{
public override object FormatObject(object obj) { return ((AsciiString)obj).ToString(); }
}This will format an AsciiString into a string, which will then be handled by PowerShell natively.
It's also possible to return IEnumerable from FormatObject, which will be expanded by PowerShell, and each resulting object is formatted by their own formatter. Those expanded object could be what is Microsoft.PowerShell.Commands.Internal.Format.GroupEntryData today.
Why it is important that we implement formatting in another class.
- First, we don't want the main assembly (e.g., the assembly containing
AsciiString) to be tied to PowerShell. By allowing it to be implemented in another class, the author can implement the formatter in a separate assembly dedicated for scripting (a kind of add-on to the main assembly). - Second, users (non-developers of the main assembly) can develop their own native formatter if they so wish.

Activity
mklement0 commentedon Mar 27, 2021
I may not have the full picture, but at least the
System.Text.Runeexample can be implemented by combining aCustomControlentry with theOutOfBandelement, as follows:Now you get the desired single-line representation with no surrounding blank lines:
To get a standard view, use
-Force:GeeLaw commentedon Mar 27, 2021
Michael Klement (@mklement0) Thanks for the pointer! I didn't know
OutOfBand(looks like this feature is little documented). This definitely solves the problem for non-enumerable types. Yet the issue for enumerable types still stand.Currently, it's not possible to prevent enumeration unless the type is
stringor the enumeration depth is exhausted.mklement0 commentedon Mar 27, 2021
That's a good point, though I wonder if this should be considered a bug: why should a type's explicitly assigned format not be honored - situationally, no less - just because it implements
IEnumerable?vexx32 commentedon Mar 27, 2021
Most likely just because the pipeline enumerates before the formatter ever gets a look at it.
mklement0 commentedon Mar 27, 2021
Rain Sallow (/u/ta11ow) (@vexx32), that's what seems to be happening de facto, but my point was that if you register formatting data for a type explicitly, it should arguably always be honored, whether the type is enumerable or not. As Ji Luo (@GeeLaw)'s example shows, the fact that it is situationally honored - when no enumeration happens to be in the picture - suggests that this is more of a fallout from the implementation than by intentional design.
GeeLaw commentedon Mar 27, 2021
After a second thought, it really is about controlling whether a type should be perceived as enumerable, not just for formatting. Suppose someone implements
AsciiString, then you want[AsciiString]$myAsciiString | foreach { <# blah #> }to not enumerate$myAsciiString.By some reverse-engineering on how PowerShell handles
string, I came up with this horrifying hack (not intended for production use): https://gist.github.com/GeeLaw/45d87803847195f9ba0f0155e00493e9The snippet makes
ArrayListmostly non-enumerable.PSEnumerableBinderto make the enumerator ofArrayListthe dummyNonEnumerableObjectEnumerator.PSPipeWriterBinderto makeArrayListpass through the pipe without being enumerated.LanguagePrimitives.GetEnumerableto make it appear non-enumerable.I'm not sure how to interpret the result of
Write-Host. When passed by pipe, the result isToString(). When passed viaInputObject, the result is joined enumerated items (perhaps due to non-overriddenToString?). And certainly Windows PowerShell 5.1 has some weird behavior...I think the issue should be changed to a feature request of controlling enumeration behavior of custom types.
mklement0 commentedon Mar 27, 2021
I think these are two aspects to consider independently:
[This may be what you have in mind] Should there be a way to signal to PowerShell that a given type that implements
IEnumerableshould not be treated as such in the pipeline?String,IDictionary,XmlNode) and include (DataTable)Should formatting data associated with a given type always be honored, irrespective of whether it is enumerable or not? (I think so)
GeeLaw commentedon Mar 28, 2021
According to the docs, every line of command is equivalent when appended with
| Out-Host, so if an object is enumerable, it will only be treated as the enumerated items, not itself.When scripting, there really isn't much difference between
List<byte>andbyte[](and evenobject[]with all items being boxedbytes). I wouldn't expect a cmdlet/function that happens to useListas its intermediate storage and direct return value to be formatted differently. But there is a crucial difference betweenAsciiString : IEnumerable<byte>andbyte[]. I would lean towards implementing the first aspect, and leaving the second as-is (an enumerable type cannot be formatted, unless the enumeration depth is exhausted).mklement0 commentedon Mar 28, 2021
I find this situational inconsistency troubling - if someone wants to use custom-formatting for an enumerable, they should be able to do so, not just when PowerShell happens not to preempt it - but it's probably not much of a real-world concern.
Either way, to get the behavior you want it sounds like two things are needed:
Provide a way to tell PowerShell that a given
IEnumerabletype is not to be enumerated in the pipeline, as data.[PSNoDefaultEnumeration] public class AsciiString : IEnumerable<byte> { ... }Make PowerShell's output formatting system respect this attribute too and then always apply any formatting data associated with such a type.
That the data and the formatting behaviors are already distinct is evidenced by the
[hashtable]example: this type is not enumerated in the pipeline, but is enumerated for formatting.vexx32 commentedon Jun 25, 2021
We discussed this today in the Engine Working Group.
I think we agree with Michael Klement (@mklement0)'s above summary here that there are fundamentally a couple of different issues converging here:
For preventing enumeration of additional types, we think allowing some method of annotating a type so that it's not enumerated in the pipeline may be of interest. We all agreed that we'd need to see some more concrete real-world examples of where the current behaviour is insufficient and how adding this kind of feature would improve things. Whether this should take the form of an attribute, or a cached list of types which can be updated via an Add/Remove method, or some other form, we're not entirely sure.
Rob Holt (@rjmholt) noted that he's raised a similar suggestion in the past, and it was at that point rejected, but we agree that it may still be worth considering. Given that this logic operates in
LanguagePrimitivesthere may be performance concerns associated with modifying the logic, so we'd prefer to see some more real-world examples of how this is impacting users before we commit to adding functionality here.For the formatting enumeration issue itself, the performance impact is less stringent, so I think perhaps implementing an attribute to disable enumeration when an object hits the formatter might be considered, but we'd need need to see a prototype or at least a suggested API surface before we can make a clear call on that side of things.
I think at this point it might make sense to split this issue into two more focused issues?
SeeminglyScience commentedon Aug 6, 2021
Apparently the formatting system already supports specifying a type as not enumerable. This doesn't control pipeline enumeration, but still it's one part of the puzzle that already works:
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 23, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.