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, Publ
Using Joey's answer you can use this function to set "aliases" to assemblies. It basically assigns an assembly to a function with the name of the given alias 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)
}
")
)
}
E.g. if you want to assign System.Windows.Forms to wforms you would call the main function as
Add_Assembly_Alias System.Windows.Forms wforms
It generates you the function called "wforms" with namespace as argument which you can use to add new objects etc. If you want to add for example a textbox object you would just have to call
$tb = new-object (wforms TextBox)
It is not much, but I think this is as close as you can get to assign an assembly to something similar to an alias. Unfortunately I didn't manage to impelement this for the direct calls of the form
[Windows.Forms.MessageBox]::Show("Hello World!")
but I hope this still helps.
Cheers, D
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.
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
You can add Powershell type accelerator (alias for type):
$accel = [PowerShell].Assembly.GetType("System.Management.Automation.TypeAccelerators")
$accel::add("mb","System.Windows.Forms.MessageBox")
[mb]::Show("Hello world")
More details can be found here and here.
WIth PowerShell 5 you can also import namespaces:
using namespace System.Windows.Forms
[MessageBox]::Show("Hello world")