PoshCode Logo PowerShell Code Repository

ConvertTo-Module by Oisin Grehan 4 years ago
View followups from Oisin Grehan | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/3656"></script>download | new post

Quickly convert a .NET type’s static methods into functions.

  1. function ConvertTo-Module {
  2. <#
  3.     .SYNOPSIS
  4.     Quickly convert a .NET type's static methods into functions
  5.  
  6.     .DESCRIPTION
  7.     Quickly convert a .NET type's static methods into functions.
  8.    
  9.     This function returns a PSModuleInfo, so you should pipe its
  10.     output to Import-Module to use the exported functions.
  11.  
  12.     .PARAMETER Type
  13.     The type from which to import static methods.
  14.  
  15.     .INPUTS
  16.     System.String, System.Type
  17.  
  18.     .OUTPUTS
  19.     PSModuleInfo
  20.  
  21.     .EXAMPLE
  22.     ConvertTo-Module System.Math | Import-Module -Verbose
  23.  
  24.     .EXAMPLE
  25.     [math] | ConvertTo-Module | Import-Module -Verbose
  26.  
  27. #>
  28.     [outputtype([psmoduleinfo])]
  29.     param(
  30.         [parameter(
  31.             position=0,
  32.             valuefrompipeline=$true,
  33.             mandatory=$true)]
  34.         [validatenotnull()]
  35.         [type]$Type
  36.     )
  37.  
  38.     new-module {
  39.         param($type)
  40.          
  41.         ($exports = $type.getmethods("static,public").Name | sort -uniq) | `
  42.             % {
  43.                 $func = $_
  44.                 new-item "function:script:$($_)" `
  45.                     -Value {
  46.                         # look mom! no [scriptblock]::create!
  47.                         ($type.Name -as [type])::$func.invoke($args)
  48.  
  49.                     }.GetNewClosure() # capture the value of $func
  50.             }
  51.         export-modulemember -function $exports
  52.     } -name $type.Name -ArgumentList $type
  53. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me