FredBainbridge

Creating classes in C# for PowerShell use

Sometimes it is just easier to write compiled code! This is a small example of how to create a custom object in C#and then use it.

C# Code Sample

using System.Text;
public class Beer
{
    public string Name;
    public string Type;

    public Beer(string NameIn, string TypeIn)
    {
        this.Name = NameIn;
        this.Type = TypeIn;
    }
}

Create a folder with the same name as the dll that gets compiled and place the newly created dll in this folder. This your new PowerShell module. Move or copy this folder to your PowerShell Module Repository of choice ($env:PSModulePath).

PSExampleBeer

Now you can instantiate the object however you want.

PSExampleBeerUsage

This is a simple example on how to use C# to write custom objects. For a more detailed approach with examples on to create a full PowerShell module check out these references:

http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/

http://www.powershellmagazine.com/2014/04/08/basics-of-writing-a-powershell-module-with-c-part-2-debugging/

And this little gem will be helpful as this .dll is now hard to find.


Share