views:

60

answers:

2

I use this code to load a .Net assembly to PowerShell:

[System.Reflection.Assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") | out-null

[System.Windows.Forms.MessageBox]::Show("Hello world")

Can I set an alias for an assembly (for example 'System.Windows.Forms' = 'Forms') so that I don't have to type the assembly full name when calling static methods like MessageBox.Show()?

+3  A: 

While you can't create some sort of namespace alias per se, you can use the following trick (taken from Lee Holmes' PowerShell Cookbook):

$namespace = "System.Windows.Forms.{0}"
$form = New-Object ($namespace -f "Form")

But that only will work with New-Object since that takes a string for the class name. You can't use that syntax with a type name in square brackets.

What you can do, however, is leave out the System part which is implied:

[Windows.Forms.MessageBox]::Show("Hello World!")

Makes it slightly shorter.

Joey
Thank you both for answering
Uros Calakovic
I didn't know about System being implied. Thanks!
Kleinux
@Kleinux: It works for referring to types, which is why you can write `[datetime]` instead of `[system.datetime]` but it won't work for loading an assembly (that is, `Add-Type -Assembly Windows.Forms` won't work).
Joey
+5  A: 

You can store the type in variable and use the variable

$forms = [System.Windows.Forms.MessageBox]
$forms::Show('Hello')

And in this case you can load the assembly like this:

Add-Type –assembly system.windows.forms
stej