Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2011-02-20
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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
…so that calls like this is possible:
[System.Windows.Forms.MessageBox]::Show("Hello!")
(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() { System.Windows.Forms.MessageBox.Show("Hello!"); } } '@
…gives you a code that when invoked, does the same thing:
$test = New-Object Test $test.hej()
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
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply