Using Classes in PowerShell for Better Data Representation

IT. Delinquent
2 min readOct 10, 2019

I found that I could use classes in PowerShell similar to how I use them in C#. I instantly wanted to play with this and I thought I would share this as well.

To create a class in PowerShell, it’s as simple as:

class PersonClass{ 

It does feel weird not adding the commas between each property of the class though 🤔

This allows a ‘Person’ to be created that has the attribute of a name and an age. Simple stuff.

Let's say I wanted to create a list of people. This would mean creating a new list of type ‘Person’. The list would look something like this:

It’s as simple as that!

What if I wanted a more complex data structure. Say I wanted a list of music artists and some of their most popular albums. I would then need to create a class to hold the artist’s info, in which one would be the list of the albums class.

Let’s create the two classes below:

This first class will hold info for a music artist. It has a name, age and an array of Album objects. The second class will hold info on a music artists album.

Let's use these two classes to build a list of MusicArtists that each have a list of Albums 👨‍💻

For the sake of space and not splitting a huge about of code at once, I’ve only added one music artist to the list.

So we now have a list of MusicArtists, that contains Roy Orbison which then has an array of the Album class.

Continuing from this, I could add as many MusicArtists to the $musicArtists list or add as many Albums to the $Albums attribute to the MusicArtists model as I like.

Searching this information isn’t as straightforward in PowerShell as it is in C# but it’s still quite easy. You can see how I get a list of all the pets that Roy Orbison has below:

$musicArtists | Where-Object {$_.Name -eq 'Roy Orbison'} | Select-Object -ExpandProperty Albums

Enjoy! 🎉



IT. Delinquent

IT Pro 👨‍💻 Dad 👀 Husband🔒 Let me know if you find anything I write to be useful... I'm still looking! Check out my website!