PoshCode Logo PowerShell Code Repository

Import-Methods (modification of post by Joel Bennett view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/969"></script>download | new post

Add functions to the scope for each static method of a type. Originally from Oisin Grehan

GREAT example: Import-Methods Math -IncludeProperties

  1. # [CmdletBinding()]
  2. param(
  3.    #[Parameter(Position=1,ValueFromPipeline=$true)]
  4.    [type]$type
  5. ,
  6.    #[Parameter()]
  7.    #[Alias("Properties")]
  8.    [switch]$IncludeProperties
  9. )
  10. BEGIN {
  11.    function MakeFunction() {
  12.     PROCESS {
  13.       $func = "function:global:$($_.name)"
  14.       if (test-path $func) { remove-item $func }
  15.       $flags = 'Public,Static,InvokeMethod,DeclaredOnly'
  16.       new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)',$flags, `$null, `$null, `$args[0])"
  17.     }
  18.    }
  19.    function MakeVariable($type) {
  20.     PROCESS {
  21.       $var = "variable:global:$($_.name)"
  22.       if (test-path $var) { Remove-Variable $var -ErrorAction SilentlyContinue }
  23.       new-variable -Name $($_.name) -Value $(Invoke-Expression "[$($type.fullname)]::$($_.name)") `
  24.                    -Description  "Imported from $($type.FullName)" -Force -Scope Global `
  25.                    -Option AllScope, Constant, ReadOnly
  26.     }
  27.    }
  28. }
  29. PROCESS {
  30.    if($_) { $type = $_ }
  31.    $type | gm -static -membertype "method" | MakeFunction
  32.  
  33.    ## Properties as variables:
  34.    if($IncludeProperties) {
  35.       $type | gm -static -membertype "property" | MakeVariable $type
  36.    }
  37. }

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