How to Define Classes in PowerShell

05. September 2016 PowerShell 0

PowerShell 5 comes with a new capability to define classes in the same way we define in C#. In this tutorial we are going to see how to define a simple class with constructor, properties, and methods.

Please check the Windows PoweShell Tutorial to learn the PowerShell basics.

Development Tool

In this tutorial I am going to use Visual Studio 2015 to edit my .ps1, .psm1 files. You might wonder why not the default ISE? Visual Studio is a great development tool which also provides the ability to edit PowerShell scripts. It gives you all the debugging tools available in ISE along with better editing and coding experience.

Visual Studio also gives you and interactive window which is similar to the PowerShell console.

Create a new PowerShell project in Visual Studio

Create a new PowerShell Script Project from Installed, Templates, Other Languages, PowerShell.

Define a class

In this tutorial we are going to create a simple class which calculates the area of a circle. We are going to add a property called radius. We are going to add a method called Area which returns the area of the circle. We will also be having a static method called CalculateArea to be used without initializing the class.

Right click on the project and add a new PowerShell Script Module called Circle. We are going to define our class definition in this module.

Edit the file as below:

Open Script.ps1 from the solution and edit it as below (if the file doesn’t exist right click on the project and add a new PowerShell Script item):


Leave a Reply

Your email address will not be published. Required fields are marked *

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