Skip to content

Is there a supported way for users to create type accelerators? #5940

@alx9r

Description

@alx9r

Consider the following enum that resides in a deeply-nested namespace:

Add-Type @'
namespace Some { namespace Deeply { namespace NestedNamespace {
    public enum AnEnum {
        One = 1,
        Two,
        Three,
        Four
    }
}
}
}
'@

"One" can be accessed from the enum using the fully-qualified type as follows:

[Some.Deeply.NestedNamespace.AnEnum]::One

The length of the namespace prefixes make use of the enum awkward. PowerShell involving such enums quickly becomes dominated by repetition of Some.Deeply.NestedNamespace. Here is a snippet that demostrates this. (I copied this from a current project, and just changed the token names.):

    if
    (
        $PSCmdlet.ParameterSetName -ne 'parameterSetA' -and
        $ParamA -notin [Some.Deeply.NestedNamespace.AnEnum]::One,[Some.Deeply.NestedNamespace.AnEnum]::Two
    )
    {
        $someVar= @{
            [Some.Deeply.NestedNamespace.AnEnum]::Three = [System.Exception]::new('message.')
            [Some.Deeply.NestedNamespace.AnEnum]::Four= [System.Management.Automation.ErrorRecord]::new(
                [System.Exception]::new('message.'),
                'Error',
                [System.Management.Automation.ErrorCategory]::OperationStopped,
                $null
            )
        }.$ParamA
    }

Ideally, this could be rewritten making use of type accelerators as follows:

    if
    (
        $PSCmdlet.ParameterSetName -ne 'parameterSetA' -and
        $ParamA -notin [anenum]::One,[anenum]::Two
    )
    {
        $someVar= @{
            [anenum]::Three = [exception]::new('message.')
            [anenum]::Four= [errorrecord]::new(
                [System.Exception]::new('message.'),
                'Error',
                [errorcategory]::OperationStopped,
                $null
            )
        }.$ParamA
    }

Add-TypeAccelerator.ps1 is available from gallery. It looks like the API used to add custom type accelerators was changed from PowerShell 2 to 3 and again from PowerShell 4 to 5. This makes me wonder the following:

  1. Is there a supported way for users to create type accelerators?
  2. Is there some other way to reduce namespace repetition when referring to types?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions