PowerShell - Convert a .NET Type’s static methods into a Module

Updated 2012/9/24: $type.Name -> $type.FullName (otherwise only types directly in System namespace are found... oops!)

Here’s something I just knocked up recently to have a nice and simple way to import groups of functions temporarily from a .NET Type as a module. When you’re done with them, you can unload at any time using Remove-Module. As the inline help mentions, you must pipe the output of this function into Import-Module to make the functions available. You have to be somewhat familiar with the methods you’re converting in order to know what order to pass parameters. Some are obvious in that they only take one argument (like Sin, Cos or Tan) but others you’ll have to double check yourself. It would have been nice to convert .NET parameters and overloads into parameter sets, but the differences between how PowerShell and the .NET compilers resolve ambiguities can be very different and would only work for mostly simple cases. Here’s how I like to quickly check method syntax:

PS C:\projects> [math]::Log

OverloadDefinitions
-------------------
static double Log(double d)
static double Log(double a, double newBase)

Here's the function itself ( also available on poshcode (updated) )

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
}

Have fun!

Emulating Bash / GNU Readline with PowerShell 3.0

Introducing PSReadline 1.0 (Beta)

This is a module that takes advantage of a new hook added to PowerShell 3.0 that allows you to completely take over the readline API. To do so, you must define a function like:

function PSConsoleHostReadline {
    [Console]::Readline()
}

The is an example of a very simple implementation. You may think it's enough, until you realise that there is absolutely zero line editing: The cursor keys don't work, no home/end, no tab completion, nothing! There's a lot more to do than just grabbing a line of text.

This module tries to emulate the Unix Bash/GNU Readline experience. Tab completion works by dumping out a long line of space-separated matches, and will only complete the current line up to the maximum amount of shared leading letters for all matches based on the current token.

Thankfully, you will also get Bash style tab completion for types, cmdlets, parameters and their values as the PSReadline module uses PowerShell 3.0's powerful and fast tab completion APIs.

This is a beta release, so expect a glitch or two. Currently all of the bindings are based on EMACS. The next release will let you define your own bindings. The EMACS bindings are documented below.

Have fun!
readline
Installation
=============

- Download ZIP file, unblock with unblock-file cmdlet.
- Extract to ~\documents\windowspowershell\modules\
  -- This should result in a PSReadline folder 

PS> Import-Module PSReadline

Known issues:
=============

- <esc> does not clear the current line
- does not use powershell history (so get-history returns nothing)
- doesn't support fancy prompt functions with newlines and/or those
  that use write-host; single line prompt function only

Credits
==============
- Miguel de Icaza (getline.cs)
  
  Thanks to his unending masochism & for donating 
  the guts of the Readline emulation, which was torn kicking &
  screaming from an old Mono REPL C# shell. Much massaging and 
  poking was needed for NT & PowerShell, but it works.

Common Bindings
=========================================
Home          Cursor Home
LeftArrow     Cursor Left
RightArrow    Cursor Right
UpArrow       History - Previous
DownArrow     History - Next
Enter         Done
Backspace     Backspace
Delete        Delete Character
Tab           Tab / Tab Complete

EMACS Bindings
=========================================
Ctrl+A        Home
Ctrl+E        End
Ctrl+B        Left
Ctrl+F        Right
Ctrl+P        History - Previous
Ctrl+N        History - Next
Ctrl+K        Kill to EOL
Ctrl+Y        Yank
Ctrl+D        Delete Character
Ctrl+L        Refresh
Ctrl+R        Reverse Search History

Alt+B         Word - Backwards
Alt+F         Word - Forwards
Alt+D         Word - Delete
Alt+BkSpc     Word - Delete Backwards

=========================================
Ctrl+Q        Quote
=========================================

About the author

Irish, PowerShell MVP, .NET/ASP.NET/SharePoint Developer, Budding Architect. Developer. Montrealer. Opinionated. Montreal, Quebec.

Month List

Page List