Call custom .NET code from powershell

Consider the following code in HelloWorld.API.dll.

namespace HelloWorld.API {
    public class Praise {
        public static string Someone(string nameOfPersonToPraise) {
            return string.Format("{0} you're awesome!", 
                                 nameOfPersonToPraise);
        }
    }
}

Make the API available with the Add-Type cmdlet. This makes all the types in a .NET assembly available in the current session.

Add-Type -Path PATH_TO\HelloWorld.API.dll

Now the static method can be called by using the :: (two colons) syntax.

[HelloWorld.API.Praise]::Someone("eric")

The output is

eric you’re awesome!

The output can be further processed by using a variable to hold it.

$praised = [HelloWorld.API.Praise]::Someone("eric")
$praised.ToUpper();

The output is

ERIC YOU’RE AWESOME!

Gotcha

When developing remember that the assembly is locked after the Add-Type until the session ends.

When to use

We use this to setup our automated (test) environment with an API. No need for custom console applications, just plain powershell.

This works for all .NET assemblies. Use it wisely.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Tooling and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s