PowerShell - set an alias for a loaded assembly

I use this code to load the .Net assembly in 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 the assembly (for example: 'System.Windows.Forms' = 'Forms'), so that I do not need to enter the full name of the assembly when calling static methods such as MessageBox.Show ()?

+6
powershell
source share
4 answers

While you cannot create any namespace alias as such, you can use the following trick (taken from Lee Holmes PowerShell Cookbook):

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

But this will only work with New-Object , since it takes a string for the class name. You cannot use this syntax with a type name in square brackets.

However, you can opt out of the System part, which implies:

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

Makes it a little shorter.

+5
source share

You can save the type in a variable and use a variable

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

And in this case, you can load the assembly as follows:

 Add-Type –assembly system.windows.forms 
+10
source share

Using Joey , you can use this function to set "aliases" to assemblies. It basically assigns a function assembly with the name of the given alias that you want.

 function Global:Add_Assembly_Alias($STR_assembly, $alias) { [string]$assembly = "$STR_assembly.{0}" $ExecutionContext.InvokeCommand.InvokeScript( $ExecutionContext.InvokeCommand.NewScriptBlock(" function Global:$alias(`$namespace) { [string](`"$assembly`" -f `$namespace) } ") ) } 

eg. if you want to assign forms to System.Windows.Forms forms, you would name the main function as

 Add_Assembly_Alias System.Windows.Forms wforms 

It generates a "wforms" function with a namespace as an argument, which you can use to add new objects, etc. If you want to add, for example, a text field object, you just need to call

 $tb = new-object (wforms TextBox) 

It is not so much, but I think it is so close that you can assign the assembly to what is similar to an alias. Unfortunately, I was not able to impose this for direct form calls

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

but I hope this still helps.

Cheers d

+1
source share

You can add an accelerator of type Powershell (an alias for the type):

 $accel = [PowerShell].Assembly.GetType("System.Management.Automation.TypeAccelerators") $accel::add("mb","System.Windows.Forms.MessageBox") [mb]::Show("Hello world") 

More information can be found here here and here .

With PowerShell 5, you can also import namespaces:

 using namespace System.Windows.Forms [MessageBox]::Show("Hello world") 
0
source share

All Articles