Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Adding references to custom types


In a great number of blog posts, I have used the Load function of System.Reflection.Assembly to load types from the .NET Framework. This (without line break) is an example that gives you access to the Forms library…

[System.Reflection.Assembly]::Load("System.Windows.Forms, Version=,
Culture=neutral, PublicKeyToken=b77a5c561934e089")

…so that calls like this is possible:


(To see the available assemblies, check the assembly folder in your Windows folder.)

When you use the Add-Type cmdlet to create your own types, the string that describes the type might need references as well. The required assemblies are specified in an array, and passed to the cmdlet as the -ReferencedAssemblies argument. This code adds a custom type…

$references = @("System.Windows.Forms")
Add-Type -ReferencedAssemblies $references @'
public class Test
   public void hej()

…gives you a code that when invoked, does the same thing:

$test = New-Object Test

The problem will show up if you have made any changes to your type and run your program again. The type called Test will already be loaded, so the Add-Type cmdlet will fail.

(If you run your program again, without changing your custom type definition, Add-Type will just be ignored – your type is there and everything is fine.)

Since types cannot be unloaded, you will need to unload your entire appdomain, and the easiest way to do this, is to close your PowerShell window. So any changes to a custom type, will be reflected in a new instance of PowerShell, thus in a new appdomain.

Categories: PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *

En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!


Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   |   |   |   Filmtips