Monday, August 13, 2007

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.

 



Tuesday, August 14, 2007 9:56:01 AM (Eastern Standard Time, UTC-05:00)
You can optimize by taking out the where statement, and use the '-membertype' paramter in get-member:

....
$type | gm -static -MemberType method | %{
...
Tuesday, August 14, 2007 1:23:34 PM (Eastern Standard Time, UTC-05:00)
thanks James, good call.

- Oisin
Oisin
Comments are closed.