PowerShell - Set Alias for Loaded Assembly

前端 未结 4 761
傲寒
傲寒 2021-02-09 00:25

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         


        
4条回答
  •  [愿得一人]
    2021-02-09 00:39

    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

提交回复
热议问题