Repository navigation
Description
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
- PowerShell classes behaviour inconsistent #2449 Exporting classes in PS modules consistently.
- Reloading module does not reload submodules. #2505 Classes in nested modules are not updated by
Import-Module -Force. - Using module statement doesn't work with ScriptsToProcess #2962 Using
ScriptsToProcesswithusing modulestops classes from being imported - Using module behavior on nested modules is inconsistent #2964
using moduleimports nested module classes in a script but not interactively. -
using module testdoesn't load the powershell class defined in 'test' if 'test.psd1' has 'FunctionToExport' or 'CmdletToExport' specified #4112using moduledoesn't load classes whenFunctionToExportorCmdletToExportare specified in the.psd1 - If a module 'test' has multiple nested .psm1 modules that define powershell classes, then
using module testcan only load the classes defined intest.psm1but not other .psm1 files #4114using moduledoes not find classes in nested modules. - PowerShell class methods cannot invoke non-exported functions. #4713 PS classes cannot invoke non-exported functions from their module (possibly a
New-Moduleproblem). - Make PowerShell Classes Exportable Module Members #6293 Making PS classes exportable module members.
Type errors
- Classes inheriting from [System.Attribute] cannot be defined and used in the same PowerShell module #1762 Custom attributes can't be defined and used in the same PS module
-
Using external types / classes in Custom PowerShell Classes (v5) results in Parsing Error #2074 Types not available at parse-time used in PS class bodies cause parse errors. Dongbo Wang (@daxian-dbw) noted that we need some types at parse-time (such as method return type) to generate the IL, but type resolution inside method/constructor scriptblocks may not be needed and be more appropriate at runtime.Noted as by design. - Defining a PowerShell class in a script causes a parser error if the class references external types that aren't currently loaded #3641 Type availability at parse-time. Need to implement the metadata reader (Use the MetadataLoadContext to restore reflection-only type discovery for mechanisms like using assembly #6653).
- See also: PSScriptAnalyzer #850
Other bugs
- Move classes error messages from runtime to compiletime/parsetime #2224 Some class errors occur at runtime when they can be detected at parse-time. (We may want to loosen the error-checking behaviour here if it makes sense to do so).
- New-Object doesn't work with classes in nested modules #2963
New-Objectdoes not work for PS classes as it does for .NET classes. - Error trying to use XmlSerializer with PS5-styled classes #5337 PS Classes in collectible assemblies cause XML serialisation problems.
- Impossible to call overridden
protected internalmethod of base class. #7622protected internaloverride doesn't work (program diverges on method call). - Class : Methods and properties can't have the same name #8235 Properties and methods with the same name are permitted in a declaration, but attempting to call the method results in an error that no such method exists.
New feature requests
- Support interface declaration using classes #2223 Interface declarations
- Parameters to methods in classes should be able to take [VALIDATExxx] attributes. #2485 Validation attributes for PS classes
- Enable native interop with static extern class methods #2876
static externmethods and struct definition in PowerShell - Add
use static <class>usage to allow static member access in PowerShell #5099 Static class member imports - Improvements for classes #6418 Other proposed class extensions.
- enum: Underlying type #8028 Support
enumtypes other thanInt32
A couple of other resources on these issues:
- Brandon Olin (@devblackops)' talk on issues with PS classes: video, code.
- The SAPIEN page on the
usingstatement: here.
Activity
sancarn commentedon May 5, 2018
Have
overridemethods 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.
christru commentedon May 16, 2018
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..
devblackops commentedon May 16, 2018
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.
christru commentedon May 16, 2018
Brandon Olin (@devblackops) as I’m litterally watching your YouTube video talk on classes. Thanks buddy!
devblackops commentedon May 16, 2018
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
IISResetMe commentedon Nov 22, 2018
Rob Holt (@rjmholt) I believe #8302 (classes don't produce valid interface property methods) should be filed under "Other bugs"
rjmholt commentedon Nov 22, 2018
Mathias R. Jessen (@IISResetMe) currently classes don't allow overrides. Wouldn't the
virtualaddition be part of the interface inheritance?IISResetMe commentedon Nov 22, 2018
Rob Holt (@rjmholt) well, we already mark all generated methods
virtual, allowing class definitions to inherit existing interfaces: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:
KirkMunro commentedon Dec 5, 2018
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:
Import-Moduleautomatically recognized psx1 files defined inRootModule, or class modules included inNestedModules, orRequiredModulesfields 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 (RequiredModulesfirst, thenNestedModules, thenRootModule, so that you can derive from other types in other modules)PSCmdletand added them to the current session without the extra work that is being done here.ClassesToExportin module manifests to identify types in modules so that implicit loading could still work, even with classes.Export-ModuleMemberhad a-Classparameter to explicitly identify which classes you want to exportOne of the drivers behind this approach is that it would do away with the need for
usingfor 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 withImport-Moduletoday. Having bothusingandImport-Moduleis 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.
KirkMunro commentedon Dec 5, 2018
On second thought, I'd prefer not having to deal with
Export-ModuleMemberorClassesToExportas 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.lzybkr commentedon Dec 5, 2018
My random thoughts:
ClassesToExportwas intentional, and type are public to help make the interactive experience good.Jaykul commentedon Dec 5, 2018
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-Moduleand alsousing module-- needing to explicitlyusinga module, even though I've already explicitly imported (orNestedorRequired) 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
ClassesToExportfeature 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 wantImport-Moduleto 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.lzybkr commentedon Dec 6, 2018
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
*ToExportproperties 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-Moduleandusing moduleisn'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.vexx32 commentedon Dec 16, 2018
Any chances we could get constructor chaining on the radar at some point, too? 😄
11 remaining items
ForNeVeR commentedon Nov 16, 2023
But this is a meta issue. What activity is expected?
JustinGrote commentedon Nov 16, 2023
Friedrich von Never (@ForNeVeR) Steve Lee (@SteveL-MSFT)
Just a casualty of an automated Process. Steve can you revert this?
mklement0 commentedon Nov 22, 2023
To add to the list in the initial post:
JustinGrote commentedon Dec 26, 2023
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?"
mklement0 commentedon Jan 25, 2024
Another one to add to the list (a
using moduleproblem with referencing customclassdefinitions in the theparam(...)block, specifically).JustinGrote commentedon Apr 16, 2024
A note to this megathread that most of these issues are not actually fixed, they were just closed by the autobot.
powercode commentedon Nov 3, 2025
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.
xtqqczze commentedon Nov 3, 2025
Staffan Gustafsson (@powercode) Should the individual issues that were labelled with
Resolution-No Activityand closed by @microsoft-github-policy-service be reopened and labeled withKeepOpen?powercode commentedon Nov 5, 2025
That seems reasonable