Skip to content

Fix Various PowerShell Class Issues #6652

Open

Description

@rjmholt

Meta-issue to track work on improving the experience of PowerShell class usage as much as possible.

Note on By-Design Behaviours

PowerShell classes currently are a bit finnicky. Some of this is a necessary pain because of the design constraints behind classes.

Classes are currently implemented as compiling to .NET IL so that we can take advantage of the .NET object model. Not doing this would mean us reinventing (and having to maintain) the wheel on essentially all object-oriented features available in .NET (or anywhere else) and paying a high runtime overhead on shimming compatibility with the .NET object model (e.g. faking inheritance from .NET classes).

Instead, we compile PowerShell classes to dynamic assemblies and bake in calls to PowerShell in the generated IL. To do this at runtime would mean either breaking dynamic- and module-scoped behaviours in classes, or emitting a new dynamic assembly every time we hit a class definition (and since PowerShell's highest compilation unit is the scriptblock, and scriptblocks are permitted in for-loops, the performance penalty here could be extreme). (I'm still a bit hazy on the details about the mechanisms here, especially in terms of why caching is made impossible by module scope or in comparison to Add-Type, but Dongbo Wang (@daxian-dbw) or Jason Shirk (@lzybkr) will be able to add to/correct me).

The need to compile classes at parse-time means the types required to define a class (in IL) must also be known at parse-time. The module-scoping issue means that a using module statement is required to import classes from modules (Dongbo Wang (@daxian-dbw) might like to add information here about the specifics governing this need), or by exporting class usage in PowerShell functions (classes having a sort of module-private behaviour).

Issues to Improve

There are, however, a few improvements possible to PowerShell classes that might not run up against the design constraints given above. Below is a list of open issues for classes in PowerShell.

Classes in modules

Type errors

Other bugs

New feature requests

A couple of other resources on these issues:

Activity

  1. added
    Issue-Meta
    on Apr 15, 2018
  2. sancarn commented on May 5, 2018

    @sancarn

    Have override methods been suggested?

    For example I have had to implement GUIs while overriding the WndProc method before. So a way to override methods would be a great addition to Powershell classes.

    Edit:

    I noticed #6418 suggested overriding property setters and getters. I suppose that is similar to this.

  3. christru commented on May 16, 2018

    @christru

    Is there any community projects that work around these issues for example? I cannot for the life of me get a decent project implemented in PS w/ classes broken out into a sensible manner without running into one of the above issues..

  4. devblackops commented on May 16, 2018

    @devblackops
    Contributor

    Chris Trujillo (@christru) You can take a look at my PoshBot module here: https://github.com/poshbotio/PoshBot

    That module is almost entirely PowerShell class based.

  5. christru commented on May 16, 2018

    @christru

    Brandon Olin (@devblackops) as I’m litterally watching your YouTube video talk on classes. Thanks buddy!

  6. devblackops commented on May 16, 2018

    @devblackops
    Contributor

    Chris Trujillo (@christru) Cool. I did the same talk at the PowerShell Summit. It is a more polished version. https://www.youtube.com/watch?v=i1DpPU_xxBc&list=PLfeA8kIs7CocGXuezOoYtLRdnK9S_Mq3e

  7. IISResetMe commented on Nov 22, 2018

    @IISResetMe
    Collaborator

    Rob Holt (@rjmholt) I believe #8302 (classes don't produce valid interface property methods) should be filed under "Other bugs"

  8. rjmholt commented on Nov 22, 2018

    @rjmholt
    CollaboratorAuthor

    Mathias R. Jessen (@IISResetMe) currently classes don't allow overrides. Wouldn't the virtual addition be part of the interface inheritance?

  9. IISResetMe commented on Nov 22, 2018

    @IISResetMe
    Collaborator

    Rob Holt (@rjmholt) well, we already mark all generated methods virtual, allowing class definitions to inherit existing interfaces:

    class PleaseDisposeOfMe : IDisposable
    {
      [void]Dispose(){ <# free unmanaged resources #> }
    }

    but since we never mark the underlying get/set methods of properties virtual (looks like an oversight), you can't actually implement an interface with a property:

    class MyPrincipal : System.Security.Principal.IPrincipal
    {
      [System.Security.Principal.IPrincipal]$Identity
      [bool]IsInRole()
    }
    
    At line:2 char:1
    + class MyPrincipal : System.Security.Principal.IPrincipal
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error during creation of type "MyPrincipal". Error message:
    Method 'get_Identity' in type '<404e3736>.MyPrincipal' from assembly '⧹powershell, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : TypeCreationError
  10. KirkMunro commented on Dec 5, 2018

    @KirkMunro
    Contributor

    Forgive some ignorance on my part, but looking at the number of issues and the complications that exist in classes in PowerShell today, I can't help but feel this is a design problem rather than a collection of issues/bugs to be addressed.

    Wouldn't it make more sense and be much easier if:

    • PowerShell had a new module type specifically for class definitions, called something like class module that could only include class definitions, with a psx1 file extension; nothing else would be allowed in these files (no functions, variables, command invocations, etc.)
    • Import-Module automatically recognized psx1 files defined in RootModule, or class modules included in NestedModules, or RequiredModules fields in a module manifest, as well as psx1 modules that don't have a manifest at all, and loaded the types defined in those psx1 files accordingly (RequiredModules first, then NestedModules, then RootModule, so that you can derive from other types in other modules)
    • PowerShell automatically identified classes derived from PSCmdlet and added them to the current session without the extra work that is being done here.
    • PowerShell automatically exported classes that are associated with cmdlets that are exported from a module.
    • PowerShell supported ClassesToExport in module manifests to identify types in modules so that implicit loading could still work, even with classes.
    • Export-ModuleMember had a -Class parameter to explicitly identify which classes you want to export

    One of the drivers behind this approach is that it would do away with the need for using for modules containing classes, and supports #requires, NestedModules, RequiredModules, which makes installing modules from the PowerShell Gallery work as expected, and everything else that people already do with Import-Module today. Having both using and Import-Module is confusing and already requires a lot of re-thinking when it comes to how you set up modules to properly load classes. It also facilitates defining an equivalent of binary modules from within PowerShell itself.

    There are more thoughts behind this, but I've shared enough to see what others think for now.

  11. KirkMunro commented on Dec 5, 2018

    @KirkMunro
    Contributor

    On second thought, I'd prefer not having to deal with Export-ModuleMember or ClassesToExport as suggested in those last two bullets at all, having psx1 files be a PowerShell-ish equivalent of a type library, with types automatically exported just as they are with dlls (ideally with something resembling public/private to control visibility). With that approach, the last three bullets wouldn't be necessary -- classes would just be loaded and available once a module was imported.

  12. lzybkr commented on Dec 5, 2018

    @lzybkr
    Contributor

    My random thoughts:

    • Not adding ClassesToExport was intentional, and type are public to help make the interactive experience good.
    • I'm skeptical that auto-loading types is a good idea, at least as a default.
    • Defining cmdlets via classes is useful and doesn't require a new module type.
    • Not being able to define functions seems a bit harsh, but I like the intention. In a new module type we could have strict functions, and these functions could even be compiled like cmdlets, convert parameters to properties, etc. This isn't exactly easy, but I think it's fairly mechanical.
  13. Jaykul commented on Dec 5, 2018

    @Jaykul
    Contributor

    Yeah, clearly it would be a great thing if Importing a module automatically included Cmdlet-derived classes as commands.

    But that circles around to Import-Module and also using module -- needing to explicitly using a module, even though I've already explicitly imported (or Nested or Required) it is one of the biggest pain point with classes for users.

    Jason Shirk (@lzybkr) I don't quite understand why you think leaving off the ClassesToExport feature and requiring me to export them by outputting them (or the user to import them with a second line of code) is a good thing: binary modules do this as a matter of course, I mean, I don't need that to result in auto-loading, but I want Import-Module to be enough so that every class I use as a parameter type (or a property of a parameter type) is available to the user.

    Of course, I also think we should actually namespace the classes by module (i.e. [ModuleName.ClassName]) -- that would certainly become critical if you started thinking about auto-loading / implicit loading.

  14. lzybkr commented on Dec 6, 2018

    @lzybkr
    Contributor

    Uh, I wasn't suggesting "outputting them" either - you define a class in a psm1, it's exported. All classes are exported, simple as that.

    I was never a fan of the *ToExport properties in the manifest, it feels like it violates the DRY principle. As an optimization, it seems fine, but I'd rather it be a build artifact.

    And classes are modeled more like an assembly - public types don't require any entries in the module manifest.

    The need for Import-Module and using module isn't really by design, it's more like we didn't have enough time to work out all the issues and people found workarounds that we live with because it seems to work. Obviously the intention was to have a more static world that you could reason about.

  15. vexx32 commented on Dec 16, 2018

    @vexx32
    Collaborator

    Any chances we could get constructor chaining on the radar at some point, too? 😄

  16. 11 remaining items

  17. added
    Resolution-No Activity
    on Nov 16, 2023
  18. ForNeVeR commented on Nov 16, 2023

    @ForNeVeR
    Contributor

    But this is a meta issue. What activity is expected?

  19. JustinGrote commented on Nov 16, 2023

    @JustinGrote
    Contributor

    Friedrich von Never (@ForNeVeR) Steve Lee (@SteveL-MSFT)
    Just a casualty of an automated Process. Steve can you revert this?

  20. removed
    Resolution-No Activity
    on Nov 28, 2023
  21. JustinGrote commented on Dec 26, 2023

    @JustinGrote
    Contributor

    Steven Bucher (@StevenBucher98) A lot of the issues on this rollup are now marked as closed. Another casualty of this "close everything" policy. At the very least, could the close bot close them as "not planned" rather than "completed?"

  22. mklement0 commented on Jan 25, 2024

    @mklement0
    Contributor

    Another one to add to the list (a using module problem with referencing custom class definitions in the the param(...) block, specifically).

  23. JustinGrote commented on Apr 16, 2024

    @JustinGrote
    Contributor

    A note to this megathread that most of these issues are not actually fixed, they were just closed by the autobot.

  24. added
    KeepOpen
    WG-NeedsReview
    on Apr 29, 2024
  25. removed
    WG-NeedsReview
    on Nov 3, 2025
  26. powercode commented on Nov 3, 2025

    @powercode
    Collaborator

    The engine working group reviewed this and concluded that it should be kept open until the PowerShell team has a plan to address the concerns in this issue.

  27. xtqqczze commented on Nov 3, 2025

    @xtqqczze
    Contributor

    Staffan Gustafsson (@powercode) Should the individual issues that were labelled with Resolution-No Activity and closed by @microsoft-github-policy-service be reopened and labeled with KeepOpen?

  28. powercode commented on Nov 5, 2025

    @powercode
    Collaborator

    That seems reasonable

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-MetaKeepOpenWG-Engine

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions