A Classy PowerShell Christmas

Well it’s that time of year again to have some holiday fun with PowerShell. This year I thought I’d give you a classy present. Or more accurately, a class-based PowerShell toy. Classes were introduced in PowerShell 5.0, primarily with DSC resources in mind, but you can use classes for all sorts of things.

In simple terms, a class is a definition of some type of object. In PowerShell you can now define a class in a simple PowerShell script file. The basic outline looks like this:

The constructor is a block of code that can create an instance of your class or object. It is completely optional as you can create an instance of your class using either of these statements:

But perhaps I  should just let you unwrap my class present.

You will need PowerShell 5.0 or later to run this file.  The script defines the class and then creates an instance of it so I’ll run the script and save the results to a variable.

image

The properties are defined in the class. When I invoke the New() method to create an instance of the object, the code in the constructor session is executed. The $this object will refer to the new instance. In my case I am invoking an internal method called GetElfName() to set the ElfName property.  If you look at that method you’ll see that it is prefaced with an object time (string). When using a method in a PowerShell class you must specify what type of object it will return, or use [void] to return nothing. Also note that if your method writes an object to the pipeline you must use the return keyword.

The List property is set from an enumeration. This is a way of creating a pre-determined array of possible values. In my case, Naughty or Nice, which is more or less randomly assigned.

The remaining properties are set by invoking the internal Refresh() method which calculates how many days are left until Christmas.  If you pipe the object to Get-Member you will see how the object matches up to the class definition.

image

I don’t want to spoil all the surprises so I’ll let you play with some of the methods. But let me at least point out the GetPresent() method. If you look at the screen shot you’ll see that there are two ways to run it. This is referred to as an overload. If you look at the code in the class definition, you’ll see multiple entries for the method, with different parameter options.

image

By the way, the method is merely returning one or several randomly selected items from another enumeration for presents. Hopefully you will get something you like.

Enjoy my gift and I wish you all the best for the holiday season and a terrific 2017.

One thought on “A Classy PowerShell Christmas

Leave a Reply

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