Creating Functions from a .NET class's Static Methods

Someone on the PowerShell NG asked recently if there was some kind of equivalent to c#'s "using namespace;" or VB.NET's "Imports namespace" statements. Well, the short answer to that is no, not really. However, you can simulate it by creating functions for each static method on the class:

  1. param([type]$type = $(throw "need a type!"))
  2.  
  3. $type | gm -static | ? {$_.membertype -eq "method" } | % {
  4.         $func = "function:$($_.name)"
  5.         if (test-path $func) { remove-item $func }
  6.         $flags = 'Public,Static,InvokeMethod,DeclaredOnly'
  7.         new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)', ${flags}, `$null, `$null, `$args[0])"
  8. }

Save this as "import.ps1" for example and use like so:

PS > . .\import.ps1 ([Math])
...

PS > Sin 1
0.841470984807897

Methods that take multiple args must have them passed as a single array:

PS > Max @(1,2)
2

Have fun!

Update: there are some interesting extensions appearing based around my initial post on microsoft.public.windows.powershell.

 



blog comments powered by Disqus

About the author

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

Month List

Page List