Loading Additional Assemblies

by Feb 18, 2013

When you want to load additional .NET assemblies to extend the types of object you can use, there are two ways of loading them: the direct .NET approach and the Add-Type cmdlet. Both examples do the same and open a MsgBox from PowerShell:

Direct .NET approach using reflection:

PS> $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
PS> $date = [Microsoft.VisualBasic.Interaction]::InputBox('What is your birthday?')

PS> $days = (New-TimeSpan -Start $date).Days
PS> "You are $days days old."

Using the Add-Type cmdlet:

PS> Add-Type -AssemblyName Microsoft.VisualBasic
PS> $date = [Microsoft.VisualBasic.Interaction]::InputBox('What is your birthday?')

PS> $days = (New-TimeSpan -Start $date).Days
PS> "You are $days days old."

There is a crucial difference between these two methods, though. When you load an assembly using reflection, you load whatever version of that assembly exists on your machine. With Add-Type, the assembly version is hard-coded to the latest assembly.

Twitter This Tip! ReTweet this Tip!