Sunday, 15 January 2017

Loading a PowerShell assembly

From time to time I write a PowerShell program which makes use of the System.Windows.Forms Namespace. As the documentation reminds us “The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system”.

In order to make use of this namespace, the relevant assembly needs to be loaded. Up until now I’ve been loading the assembly with the .NET Framework class:

[System.Reflection.Assembly]:: LoadWithPartialName ("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]:: LoadWithPartialName ("System.Drawing") | Out-Null

Use of the "Assembly" class is discouraged as this API is now obsolete so I now use the "Add-Type" cmdlet:

Add-Type -AssemblyName "System.Windows.Forms";
Add-Type -AssemblyName "System.Drawing";

Loading the assembly with the name alone doesn’t take into account any versions. So, if you wish to load an assembly with a particular version, a different syntax of the command will be required. For the scripts I’m writing, this hasn’t given me a problem although I guess I may have to think about this issue sometime in the future.




Keywords: load powershell assembly