Working with .Net assemblies in PowerShell

It’s quite easy to load and use .Net assemblies in Windows PowerShell, which of course is one of the main selling points of the script language. In this post I’ll show a few examples.

Listing all loaded assemblies:

PS> [AppDomain]::CurrentDomain.GetAssemblies()

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Conso...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c5619...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Management.Automati...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Configuration.Insta...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Comma...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Secur...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\Microsoft.PowerShell.Comma...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Management\2.0.0.0_...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.DirectoryServices\2...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c5...
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c...

To load a new assembly, do the following:

[reflection.assembly]::loadfile('C:\...\bin\Entities.dll')

When an assembly has been loaded, types and code in it can be used with the new-object Cmdlet, for example:

PS> $obj = new-object Entities.Affär
PS> $obj.Affärsnummer = “2323232”
PS> $obj.Kundnamn = “Acme”
PS> $obj

Kundnummer :
Kundnamn : Acme
Organisationsnummer :
KontaktpersonKund :
Referens :
Affärsnummer : 2323232
Fas :
Betalningsvillkor :
Status : None
Fakturaaddress :
Fakturor : {}
Id : 0

PS> $obj.Validate()
Exception calling “Validate” with “0” argument(s): “Affärsnummer: Felaktig data: Affärsnummer skall alltid vara 9 siffror”
At line:1 char:14
+ $obj.Validate( < <<< ) [/code] Pretty cool, huh? (BTW, Validate() is a method on the "Affär" class.) Also note that some command completion works with imported types. For example, if I type "$obj." and then press TAB, then the console will cycle through the available members of the type in question. There's more to write about this interesting subject, so more posts will come... /Emil

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.