PowerShell: call your own DLLs

Firstly credit for the syntax.

I want to write a library in C#, and invoke it from PowerShell. Let us also say┬áthis is a bare-bones Windows 7…10 PC, and therefore has no C# compiler, but obviously does have PowerShell natively, even if the versions vary (2-5).

C# Compiler

In fact every Windows PC has a C# compiler, in the framework folder, e.g. [C:\Windows\Microsoft.NET\Framework\v4.0.30319]. I did not want to add this to the path. I also wanted to understand the minimum set of C# artifacts to compile code. Turns out there are just 2 required: [csc.exe] and [cscui.dll]. I copied this into my PowerShell working folder. So let us say we have a library [MathLib.cs] (see the credit). You can compile this thus:

.\csc.exe /target:library MathLib.cs

, which results in this:


Load and call a DLL from PowerShell

You can then load it using…


and invoke it like this:

[MathLib.Methods]::Sum(10, 2)

, or load it like this:

$mathInstance = new-object MathLib.Methods

and invoke it like this:

$mathInstance.Product(10, 2)


Again, all credit to Lee Holmes – I’ve just taken what he did and re-presented for my preferences.