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.

Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. 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 comment

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