PoshCode Archive  Artifact [6b66a58ca8]

Artifact 6b66a58ca8149254776149b01476465256123c23a3e0a928d75a752815c69f95:

  • File ConvertTo-Module.ps1 — part of check-in [15cfef6a99] at 2018-06-10 13:28:52 on branch trunk — Quickly convert a .NET type’s static methods into functions. (bugfix update: $type.Name -> $type.FullName) (user: Oisin Grehan size: 1827)

# encoding: ascii
# api: powershell
# title: ConvertTo-Module
# description: Quickly convert a .NET type’s static methods into functions. (bugfix update: $type.Name -> $type.FullName)
# version: 0.1
# type: function
# author: Oisin Grehan
# license: CC0
# function: ConvertTo-Module
# x-poshcode-id: 3661
# x-archived: 2016-03-17T04:41:05
# x-published: 2013-09-24T13:43:00
#
#
function ConvertTo-Module {
<#
    .SYNOPSIS
    Quickly convert a .NET type's static methods into functions

    .DESCRIPTION
    Quickly convert a .NET type's static methods into functions.
    
    This function returns a PSModuleInfo, so you should pipe its
    output to Import-Module to use the exported functions.

    .PARAMETER Type
    The type from which to import static methods. 

    .INPUTS
    System.String, System.Type

    .OUTPUTS
    PSModuleInfo

    .EXAMPLE
    ConvertTo-Module System.Math | Import-Module -Verbose

    .EXAMPLE
    [math] | ConvertTo-Module | Import-Module -Verbose

#>
    [outputtype([psmoduleinfo])]
    param(
        [parameter(
            position=0,
            valuefrompipeline=$true,
            mandatory=$true)]
        [validatenotnull()]
        [type]$Type
    )

    new-module {
        param($type)
         
        ($exports = $type.getmethods("static,public").Name | sort -uniq) | `
            % {
                $func = $_
                new-item "function:script:$($_)" `
                    -Value {
                        # look mom! no [scriptblock]::create!
                        ($type.FullName -as [type])::$func.invoke($args)

                    }.GetNewClosure() # capture the value of $func
            }
        export-modulemember -function $exports
    } -name $type.Name -ArgumentList $type
}