PoshCode Archive  Artifact [1d553a6724]

Artifact 1d553a6724f150f46879d1600eb67b13a63eac28877f6b79eb86da33877f00f3:

  • File Import-Methods.ps1 — part of check-in [c075e7be39] at 2018-06-10 14:27:36 on branch trunk — Add functions to the scope for each static method of a type. Originally from Oisin Grehan (user: Joel Bennett size: 1592)

# encoding: ascii
# api: powershell
# title: Import-Methods
# description: Add functions to the scope for each static method of a type. Originally from Oisin Grehan
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# x-poshcode-id: 969
# x-archived: 2011-05-04T04:57:28
# x-published: 2011-03-20T07:50:00
#
# GREAT example: Import-Methods Math -IncludeProperties
#
# [CmdletBinding()]
param(
   #[Parameter(Position=1,ValueFromPipeline=$true)]
   [type]$type
,
   #[Parameter()]
   #[Alias("Properties")]
   [switch]$IncludeProperties
)
BEGIN {
   function MakeFunction() {
    PROCESS {
      $func = "function:global:$($_.name)"
      if (test-path $func) { remove-item $func }
      $flags = 'Public,Static,InvokeMethod,DeclaredOnly'
      new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)',$flags, `$null, `$null, `$args[0])"
    } 
   } 
   function MakeVariable($type) {
    PROCESS {
      $var = "variable:global:$($_.name)"
      if (test-path $var) { Remove-Variable $var -ErrorAction SilentlyContinue }
      new-variable -Name $($_.name) -Value $(Invoke-Expression "[$($type.fullname)]::$($_.name)") `
                   -Description  "Imported from $($type.FullName)" -Force -Scope Global `
                   -Option AllScope, Constant, ReadOnly
    }
   }
}
PROCESS {
   if($_) { $type = $_ }
   $type | gm -static -membertype "method" | MakeFunction

   ## Properties as variables:
   if($IncludeProperties) {
      $type | gm -static -membertype "property" | MakeVariable $type
   } 
}