Identifying Essential Add-Type Statement

by Nov 27, 2015

When you access .NET types and objects directly in your PowerShell code, you must make sure that the appropriate .NET assemblies are loaded. If you do not, you risk that your script will break once it runs in a simple PowerShell console.

Here is a way how you can find out the names of the assemblies required for objects and types in use. This would tell you what the assembly name is for the object stored in $window variable:

$window = New-Object -TypeName System.Windows.Window
$window.GetType().Assembly.FullName.Split(',')[0]

And this is how you find the assembly name for types:

[Windows.MessageBoxButton].Assembly.FullName.Split(',')[0]

[System.Windows.Forms.OpenFileDialog].Assembly.FullName.Split(',')[0]

Once you know the assembly name, make sure you add a statement like this before you use the objects or types:

Add-Type -AssemblyName PresentationFramework

Twitter This Tip! ReTweet this Tip!