Friday, April 4, 2014

PowerShell Tip #1: Loading custom assemblies


PowerShell is a great trick to have in your bag, it allows easy and flexible scripting using SharePoint objects. Whether you're automating a certain one-off(ish) task, or just debugging a certain strange behaviour, it is always the tool I resort to.

This time, I was having an issue with an Event Receiver. PowerShell came to the rescue!
(...)


Something wasn't right, even thought it should be. I wanted to isolate the issue, validate the code being used, the method being called, did what it was supposed to do. This way I could be sure it was something to do with the Event Receiver's configuration and not the code.

In order to do that, I needed to load my custom assembly and call the method in question. The assembly was deployed to the GAC.

Using PowerShell 3.0 or up, you have the Add-Type cmdlet available:

Add-Type -AssemblyName Org.Proj

More info on TechNet, here

On previous versions, the easiest way was using the following (although deprecated for many years, it seems):

[System.Reflection.Assembly]::LoadWithPartialName("Org.Proj")

To use your methods and properties, just use:

[Org.Proj.Module.PublicClass]::Method()
[Org.Proj.Module.PublicClass]::Property

And if your methods use any SharePoint object as input or output, you can just use the objects you get from PowerShell using the SharePoint cmdlets with no problems.

No comments:

Post a Comment