Monday 21 January 2013

Working with Forms Outside of Powershell ISE

Another issue I encountered when I was first starting out with Powershell scripting was a strange error that occurred when I loaded any of my scripts that used forms. (Forms are used to provide a graphical user interface (GUI) for the script - eg. input boxes, list boxes, pop up messages etc). The issue only occurred when I ran the script outside of the Powershell editor - Powershell ISE.

The following error would occur when the script started;

New-Object : Cannot find type [System.Windows.Forms.Form]: make sure the assembly containing this type is loaded

This error would occur hundreds of times, once for every line of code that referred to System forms that were being used.

After a little investigating, I discovered that you must load the .NET Framework classes being used at the beginning of the script. This is easily accomplished with the following lines of code;


[void]  [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void]  [System.Reflection.Assembly]::LoadWithPartialName("system.net.mail")

This will load all the system form assembly's required to use custom windows forms in your script.

Note: The [void] text simply prevents any informational messages from being displayed on the screen when the classes are loaded.

No comments:

Post a Comment