[PowerShell] How to Create Simple Class

As a C# developer, I think that I should need to know how to create a class in PowerShell. Since Windows PowerShell 5.0, it adds the ability to create a class. With a class, we could do the coding more like C# (this is a good news to a C# developer like me, lol). We could create methods properties, enums, and other things to Class in PowerShell.

The first thing we need is, use the Class keyword. This is a sample on it,

Class Vehicle {

}

Within the brace, we could add our items in it. Be careful when we create object in PowerShell. The Windows PowerShell automatic type system works remarkably. it allow us create any variable without specify its type. Everything will simply be a System.Object. if you have a string, an int, or a DataTime object, the best practice (or you must) is to specify that type so that things will work well.

Because I am creating a class for a vehicle, I could create something like, Vehicle Registration Plate, Model, Year, Number of Doors, Number of Wheels, Seating Capacity, Engine Displacement, Engine Max Torque….etc

[String]$RegPlate
[int]$NoOfDoors
[datetime]$Year
[String]$Model
[int]$numberOfWheels = 4
[int]$numberOfDoors = 5

I can then use the New-Object cmdlet to create an instance of the Vehicle class,
$myVehicle = New-Object Vehicle

I can now get the default values of all variables (class properties) in $myVehicle.

Now I can simply assign values to $myVehicle,

Now I could see all the updated values,

That is how you create a simple class in Windows PowerShell 5.0. Let’s talk about adding more stuff to the class later. Hope you enjoy and learn the PowerShell with me.

 

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.