How to call a .NET method in PowerShell 2.0?

As you know, PowerShell is built on top of .NET. One can use the features of .NET Framework and can use any assemblies in .NET. This includes the built-in assembly as well as the user created one. In this post, I would like to describe how to call a static method defined in an assembly.

I would like to take the System.Windows.Forms.MessageBox.Show() method as an example. We use the :: operator to access the static methods in PowerShell. To begin with we use the following code in PowerShell to display a message box which says ‘”Hello World”

PS C:\> [System.Windows.Forms.MessageBox]::Show(“Hello World”)

However, this will not work as expected. When you execute the above command in PowerShell, it will give the following error

Unable to find type [System.Windows.Forms.MessageBox]: make sure that the assembly containing this type is loaded.
At line:1 char:34
+ [System.Windows.Forms.MessageBox] <<<< ::Show("Hello World")
    + CategoryInfo          : InvalidOperation: (System.Windows.Forms.MessageBox:String) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

Don’t panic. This is because PowerShell did not recognize the MessageBox.Show() method defined in the System.Windows.Forms namespace. To make this work, we need to load the System.Windows.Forms assembly like we will do in any .NET application. The following command will load the assembly.

PS C:\> Add-Type –AssemblyName System.Windows.Forms

Once you load the assembly through Add-Type cmdlet, you can use the command to display a message box.

PS C:\> [System.Windows.Forms.MessageBox]::Show(“Hello World”)

This will display a message box with an OK button and “Hello World” as the text.

image

This is not over yet. Now how to use the enumerations like MessageBoxButtons and MessageBoxIcons in a message box. Something like:

System.Windows.Forms.MessageBox.Show(“Hello World”, “Simply Hello World”, MessageBoxButtons.OkCancel, MessageBoxIcon.Information)

We use the same operator (::) to access the enumerations as well. The sample command is given below:

PS C:\> [System.Windows.Forms.MessageBox]::Show(“Hello World”, “Simply Hello World”, [System.Windows.Forms.MessageBoxButtons]::OkCancel, [System.Windows.Forms.MessageBoxIcon]::Information)

Now that looks better, doesn’t it?

image

I know, the next question will be “how will you handle the result from MessageBox?”. It is simple, store the result in a variable using the following command

PS C:\> $result = [System.Windows.Forms.MessageBox]::Show(“Hello World”, “Simply Hello World”, [System.Windows.Forms.MessageBoxButtons]::OkCancel, [System.Windows.Forms.MessageBoxIcon]::Information)

Once we get the result, check the value and perform the action as given in the sample below:

if($result -eq [System.Windows.Forms.DialogResult]::OK) {Write-Host "You clicked OK button"}

I hope this helps you. Let me know if you have any feedback.