Quantcast
Channel: Nivot Ink - PowerShell 3.0
Viewing all articles
Browse latest Browse all 4

Updated Type Accelerator functions for PowerShell 3.0 and 4.0

$
0
0

I noticed that my old type accelerator functions don’t work anymore in later versions of powershell due to some internal changes for caching. This sometimes happens when you tinker when innards like that.

Here's the source, but it's also up on poshcode.org.

#requires -version 3

function New-TypeAlias {

    param(
        [parameter(mandatory, position=0)]
        [validatenotnull()]
        [type]$Type,

        [parameter(mandatory, position=1)]
        [validatenotnullorempty()]
        [string]$Name
    )

    $accel = [psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")
    $accel::add($Name, $Type)

    # reset cache
    $accel.getfield("allTypeAccelerators", [reflection.bindingflags]"nonpublic,static").setvalue($accel, $null)
}

function Get-TypeAlias {

    param(
        [parameter(position=0)]
        [validatenotnullorempty()]
        [string]$Name = "*"
    )
    $dict = [psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::get
    $matches = $dict.Keys | ? { $_ -ilike $Name }

    if ($matches) {
        $dict.GetEnumerator() | where key -in $matches
    } elseif (
        -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Name))
    {
        write-error -Message "No exact match found for alias '$Name'"
    }
}

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images