Skip to content

Classes inheriting from [System.Attribute] cannot be defined and used in the same PowerShell module #1762

@SteveL-MSFT

Description

@SteveL-MSFT

Steps to reproduce

set-StrictMode -Version 'Latest'
$PSDefaultParameterValues['*:ErrorAction'] = 'Stop'

class TestAttribute : System.Attribute {
}
class TestClass {
[int] [TestAttribute()] $i = 5
}

S C:\Users\scbaker> Import-Module E:\tmp\Test-Module2.psm1

Import-Module : The invoked member is not supported before the type is created.
At line:1 char:1

  • Import-Module E:\tmp\Test-Module.psm1
  • CategoryInfo : NotSpecified: (:) [Import-Module], NotSupportedException
  • FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.ImportModuleCommand

Scotia Baker:

Because class names aren't visible outside their defining module, the only workaround I've found is using Add-Type. Defining the attribute in another module using PS5 class support does not work due to lexical scoping of class names.

ISSUE:

A custom attribute class cannot be defined and used within the same PowerShell module.

IMPACT:

(1) Debug time diagnosing the issue. The import failure does not say what member or type is involved, making debugging difficult.

(2) An extra module must be created to define attribute classes regardless of logical code layout.

The primary impact is in the debugging time; an extra module may be ugly but it's easy enough. A fix for the issue is of course preferred.

Metadata

Metadata

Assignees

No one assigned

    Labels

    KeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions