I recently got curious about how a powershell class works. After digging a bit into it, I have to admit: I actually love it!
Using a PowerShell class allows us to create PowerShell objects, but in a way cooler and faster way! How do we create a powershell class? what are the new possibilities that a powershell class offers us? What is actually a powershell class? a constructor? how do we instantiate a class? Why should I even care about writing a powerShell class?

I will answer all of these questions throughout this post, by focusing the content of this article on two main topics:

  • The basics of a PowerShell class.
    • Which will cover the vocabulary, and how we use these new keywords.
  • A practical use case for using a powerShell class in a real environment.
    • Create a powershell class in order to fetch, or create a active directory computer object.

I will also try to answer the following broader questions I had, ever since I first heard talking about classes;

  • Why should we even use a powershell class,  or actually use classes in general?
  • Where is that thin line located that makes us choose from using a regular function to using a powershell class?

This post has been written using the PowerShell v5 April 2015 preview. Some of the concepts / topics covered in this post might be subject to change until the final release get published.

PowerShell Classes: A concrete example

The main objective here, is that after reading this blog post, everybody understands a bit about what a powershell class actually is. For that I will first cover the basics. The vocabulary will be explained (Since not all of us are developers, and as a Powershell Scripter, we take a big step towards the developer’s universe). It seems important to me, to explain the basic vocabulary that help’s us understand some of these new concepts. What is a powershell class? instantiation, enums, $this, etc… . We will do that, but we will try to build something solid that you can actually use in your own test/production environment.(Or at least, something similar).

Computer class

We are going to build a “Computer” class together. While going forward in the learning process, we will expand the functionality of our main class.

I will cover the following powershell class related topics:

  • Create a powershell class
  • Return an object that contains specified properties
  • Create a powershell class constructor
  • Instantiate a Powershell class
  • Assign values to properties
  • Create a powershell class method and check for a variety of things.

At the end of this post, we will have a class that will get and set properties, return an object with our default properties. To make this example more ‘real’, I will build a class that will gather information from my local Active Directory. If the computer is not existing, the class will create the computer object in the AD, assign it a set of default properties (new name, owner, description etc.. ) and  all of that using a PowerShell class.

If you are already familiar with concepts and vocabulary such as ‘Instantiation’,’Class’,’Constructors’,’overloards’ etc… You can skip the first part of this article and rush to ‘PowerShell Classes: Introduction‘ where I cover the core concepts of a PowerShell class.

Powershell classes: The basic vocabulary

If there is one thing that can be confusing when you start to learn something new, and what will make things way harder if you don’t have it, is defenitly the vocabulary. I think that it is a bit like speaking a foreign language; If you don’t understand the vocabulary, you won’t understand the message.

Same thing here for Powershell classes. If you don’t know the meaning of the words that are used to describe some technical elements, you won’t be able to fully understand the concepts of it.

Using classes in PowerShell is another step forward towards the developer’s world for IT Pro’s, System engineers and System admins (Did someone say “Devops”?) . This means that a lot of developer concepts, and there related vocabulary are becoming a part of our world.

Powershell Classes really makes us jump this gap, and embrace this other world. I see this as a concret example of Devops in action.

What is a powershell class?

What is a powershell class actually? before even starting to talk about code, let’s take a short minute and focus on the concept of classes.

A class, would be a ‘Blue Print‘ of a specefic object. For example, in the Active Directory environment, there must be a Class called user, that defines what the object “User” must look like. We can logically think of properties like: Name, surname, address, LoginID, phone number, Managed by, memberof, password etc… Each time we create a new user in active directory, we use the same pattern, and the same manadatory parameters. Once all the required properties are given, we have our new user (thus our ‘new object’) that is created.

Using a class, ensure us to use always the same pattern to create our object, and always returns an object.

If we compare this behaviour to a regular function, we can already see one big difference: The Function does not have to return an object.

Remember this: A class, is a blue print for a specefic object.

powershell class Properties

A property would be an information concerning a specific subject.

A red house.

Red would be a property of the house.

In dotnotation, we would access the house coulor like this –> $House.color

PowerShell wise we use properties ALL the TIME (Even without using classes). When you query for a computer in you active directory using Get-ADComputer, you get an object containing properties. Querying WMI? An object with properties is returned. Querying ConfigMgr information, objects with properties again.

powershell class Methods

A method would be an action that the house would do.

For example OpenGarageDoor would be the action of opening the garage door.

Another example would be “RepaintHouse“, which would for example, change the house color property.

To access a method, we would do the following:


We could repaint the house in pink using the following dotnet notation.


If you have worked with WMI and powershell before, you have most likley already have used methods like .Set .put() or Update().

powershell class instantiation

A powershell class works actually just like powershell Objects. They need to be present somewhere in memory. The intiantiation of a class, would be the action of putting a new copy of that class into memory.

If we continue with out house example. Let’s say you already have a house ($House). But you really love the mountains, and the fresh and cold air when you are snowboarding down the hils in the French Alpes, and for that reason, you decide to buy second house at the mountains. A winter house.

Your new winter house, has the same ‘features’ (read attributes) as your main house. It has a color, and a garage door. Once you bought it, you can say that you instanciated your new WinterHouse, and it comes with a default color, and the ability to open the garage door (When there is not 2m of snow in front it;)).

The very basic of a powershell class instantion  would be as follow:

powershell class Void

Void is concept that has never really been used in PowerShell until now.  Void is used for methods. Generally, you want your methods to return something. A value for example. In some cases, you don’t care about that. You just want you method to do something, and don’t expect anything to come back from it.

For example, when you open the garage door from your house, you want it to open. That’s it. You don’t necessary need a voice going off in the background saying ‘Your door is now open’ like in the old scify movies.

Void in french, would be “rien/vide”
Void in German would be “Leer”

powershell class constructor

A powershell class constructor is the portion of the code that influence how you instantiate a powershell class. If we continue with the House example, we could have multiple ways to build our house.
Let’s say, we have a specefic way to construct a WinterHouse, which will need to be warm, well isolated, with a fire place etc.. and another way to construct a SummerHouse, which will have a garden, pool, fruit trees etc… But both of them will share some elemental properties such as “Roof”, numberOfWindows, Garage, color…  and for example have the same OpenGarageDoor() method to open the garage.

You can build more or less the same house, but in two different ways to ‘construct’ it.

It will make more sense a bit later when you see the practical example.

Powershell classes: Introduction

How to create a powershell class?

You can create a very basic empty class as follow:

Even though you won’t do much with this class like as it is, but this is the very basic stuff you need to have in order to create a class.
You might see the resemblance with a Function, workflow, or Configuration if you are already used to PowerShell. The Keyword syntax that you must use quite often by now. You can actually rely on your existing powershell knowledge gained through the years and put a lot of these concepts in use while writing powershell classes. PowerShell classes is just another building bloc on top of the existing PowerShell concepts.

Adding properties to a PowerShell class

You can add properties to a powershell class as follow:

Every computer that you know has attributes. You generally give it a name, a description, what type of a machine it is, who’s computer is it (owner).

Instantiating a PowerShell class

Now that you have added your first properties to your default class, you would like to see the results. Just to be sure that it actually works. For that we need to bring in that new concept of instanciation.

Instantiating a powershell class, is as I mentioned earlier, the action of putting a new copy in memory of our original object (Remember the new $WinterHouse in the French alps). If we continue with out “Computer Class” example, and let’s say, I just bought my self my very first and brand new computer. I will instantiate my Computer class using the following syntax:

if we take a look into our variable $NewComputer, we will have an empt object returned with our 4 basic properties.

PowerShell class instantiation

PowerShell class instantiation

In the ‘old’ powershell 2/3/4 way (which is not the wrong way) I would written it like this:

Adding methods to a PowerShell class

Our computer can do a lot of things. We can Turn it on, turn it off, reboot it etc… If a computer reboots, we might want to keep that information stored somewhere, just to be able to identify a machine that reboots a lot.

Let’s add a new property that will contain the total number of reboots of the computer and I will name it ‘$Reboots’

This is what the class will look like with that new method.

If we instantiate a new computer assign it to a variable $NewComputer and make it reboot by using the $NewComputer.Reboot() method, we will have the following:

PowerShell classes Methods

PowerShell classes Methods

Notice how I have used $This.Reboots++ to increment the $Reboots variable. Basically, $This referes to a variable that has been declared at the begining of the PowerShell class.

Adding values to our properties

Now that we have instantiated our Computer Class into the $NewComputer value, and rebooted it once, we can actually go and set the rest of the properties by using the dot notation.

If we take a look at our $NEwComputerVariable, this is what it will look like:

PS C:\WINDOWS\system32> $NewComputer
Name : DC01
Description : Domain Controller of Basel Site
Type : Server
Owner : Stephane van Gulick
Reboots : 1

Powershell class constructors

It is nice to be able able to work with objects in PowerShell, but needing to instantiate the class first and assign it to a variable, setting all the properties values afterwards is a bit too much effort. We can make the things easier and more straight forward when we use ‘powershell class constructors‘ .

We have been instantiating our classes using the [Computer]::new() constructor‘ until now. Writing new constructors in our powershell class will allow us to instantiate our class, the [Computer] class, in a different way. In other words, we will be calling our new::() constructor differently.

Basically, we could instantiate a new powershell class and assign directly values to some of the properties. In the example below, I have build a constructor that accepts 3 properties: $Name, $Description, and $owner

A constructor must always have the same name as the powershell class. In our example, the class is named Computer, and the constructor is also named Computer. We can have several constructors. Each of the powershell class constructor must have the same name, but their parameters will vary in number and / or type.

While we write the call to instantiate our class using our new:: constructor, we can see that intelisense has found our constructor.

PowerShell class constructor declaration and call

PowerShell class constructor declaration and call

Finally, this is how we would call our new constructor for the class [computer] and the object that would be returned from it.

PowerShell class constructors

PowerShell class constructors

Powershell class constructor using overloads

Ok, we have done quite some road until now. But let’s make this class a bit more use full to us, and try to make something that could potentially be used later on.

Instantiating a computer class, and giving it a name a description and a owner is good to get logic behind using the PowerShell classes mecanism. But that code won’t really help us in our environment. Let’s enhance our existing code by adding an extra constructor!

In my environment, I do have quite some servers that are running different services; Sharepoint, Configuration Manager, Active Directory, SQL etc…
To illustrate the utility of build constructors in Windows Powershell, I will add two constructors:

  1. The first one will be a sort of ‘custom‘ Get-AdComputer, that will fit gather information out of active directory when I call my Constructor with only one parameter ($Name). The powershell constructor will gather information from AD, and tailor the object that is returned to fit our corporate standards.
  2.  The second powershell class constructor will be use to create a new computer. It will automaticall provision a Computer object in the AD, and fill it with specific data ($Name, $Description,$Owner) and calculate some specific data ($Type).

We can see here that I added a 2 new constructors, which both have the same name as the class, but they different on their parameters:

  • $Name

Which does the following:

  1. Get the name, description and owner of a computer object
  2. According to the OS, it will set the value of type to either, Server, Laptop, or workstation.
  • $Name, $Description, $Owner, and $Model.

Which does the following:

  1. Check if the AD Computer Name is not already existing.
  2. Attempt to get the Owner of the Computer by using the “Get-ADUser” powershell cmdlet.
  3. Creates the AD computer account with the information provided as parameter.

I have voluntarily left the model empty and cover that information in another blog post.

When we will call the new:: constructor, we will have the choice between our two constructors as highlighted in the next screen shot:

PowerShell class 2 constructors

PowerShell class 2 constructors

We can see on the screen shot above that the intellisense offers us the choice between the two constructors:

  • one with one parameter (string Name)
  • Another one with five parameters (String Name, String Type, String Description, string Owner, String Model)

Here under is the results of the call to the longest of the constructors. It created a new computer Object, assigned ‘Kung Lao’ as the owner of the object, and returned a object with our different properties.

PowerShell class constructors results

PowerShell class constructors results

The concept of creating a second constructor (or more) in a powershell class is called ‘overloading’ a class. Our class [computer] has two overloads.

The end?

So why should we use PowerShell classes?

Basically, you don’t have to, but we saw that we could make things easier by compating everthing in one single class, and from their, either get information concerning a Computer existing in our Active directory, or by creating a new object for it, and returning a workable object with it.

As for the second question, it will be answered in the part 2 of this blog post, when we would have covered what’s rest for us to learn on PowerShell classes and how to create a class in PowerShell.

Stay tuned, and thanks for reading!


Read more about PowerShell Classes

  • Official About_Classes help –> About_Classes
  • Trevor Sullivan Youtube channel (Good introduction to classes) –> Youtube channel
  • [French] Presentation de Fabien dibot et Pascal Sauliere lors de techDays –> link
By | 2016-10-19T21:00:13+00:00 June 8th, 2015|PowerShell, PowerShell Classes, Series|17 Comments

About the Author:

Stéphane is a dynamic and passionate Cloud and datacenter Microsoft MVP since. He is the founder of the Basel PowerShell user Group (BPUG), the co-founder of the French Speaking PowerShell UserGroup (FRPSUG), author, blogger, and received the community award "PowerShell Hero" from PowerShell.org. Stéphane has implemented microsoft infrastructure solutions in various countries of Europe and is currently working in Basel / Switzerland. Stéphane help his clients to reduce their global infrastructure costs by implementing Microsft infrastructure solutions by combining great products such as System Center, Windows Server, with heavy automation using Windows PowerShell. Stéphane loves languages, Belgium beer, French cheese and French Wine. If any of these topics are of your interest, don't hesitate to come and say hi.


  1. David D. September 6, 2018 at 7:24 pm - Reply

    Good article. Question – is there a way to have a « temporary » variable in a method?
    For instance
    Class Target {
    [void]Update() {
    If ($this.status= »up ») {$temp= »U »}
    elseif ($this.status= »down ») {$temp= »D »}
    else {$temp= »X »}

    It just makes it a little neater to read than
    If ($this.status= »up ») {$this.history=$this.history+ »U »}
    elseif ($this.status= »down ») {$this.history=$this.history+ »D »}
    else {$this.history=$this.history+ »X »}

    • Stephane September 6, 2018 at 8:01 pm - Reply

      hi david. yeah that should work actually

      • David D. September 6, 2018 at 9:58 pm - Reply

        Thanks Stephane, yeah I see that now, although there are some caveats to it, I think. For instance, the variable name can’t be the same as a field name ($status is a no-no, but $tempstatus seems to be OK). Do you know of any good, thorough documentation on the Class abilities in PS5? It all seems to be scattered, and some of what I found at Microsoft is a bit, eh, dry. Classes in Powershell look like they will be really, really handy, even if I skip the OOP part and just use them as dumb “record” types like we had in Pascal long ago. 😉 Even that’s better than what we had with PSObject, IMHO. If Microsoft would soften up their scoping a bit (ie – let us define a GLOBAL or SCRIPT scoped variable once instead of having to prepend $GLOBAL: or $SCRIPT every single time it’s used), I’d be one happy camper.

  2. Jake November 2, 2017 at 7:50 pm - Reply

    This is a great article, however being fluent in both PowerShell and C# I think the use of classes creates a state of ambiguity and over-complicates the use of PowerShell. If you are going to go as far to write classes in PowerShell, then you may want to look at C#, but that would undermine the whole purpose of PowerShell wouldnt it? I mean, to imo you are just writing PowerShell in C# style. I was under the impression that PowerShell was supposed to simplify and strengthen coding for the Admin, not force you to make more choices. For me, I still dont see a real purpose for classes in PowerShell, but maybe its because I have been working in both languages so long they kind of just run together. Maybe I am over-complicating and over-simplified process?? Who knows, but I will still with modules and functions or C# flavored modules.

    • Stephane November 27, 2017 at 11:48 am - Reply

      Hi Jake, thanks for your very interesting comment.

      I have to disagree with you on several points, especially when you say it over complicates our scripts.

      Imo using classes in powershell scripts really reduces the number of different functions you need to write, and you can combine the complete functionality in one and single class using different methods which would have previously needed to be writen in several functions. (You can see here a concrete case where I have writen a single class including a lot of functionality which would have turned to be several functions –> http://powershelldistrict.com/managing-hosts-file-using-powershell-classes/ )

      The fact that you can take advantage of inheritance also simplifies the script writing process imo. Where I agree with your train of thought, is that a powershell scripter is normally seen as an admin writing only functions and modules, and does really deal with OOP. If there is a OOP learning curve (or no OOP knowledge yet/at all), then yes, there can be an over complication.

      Never the less, turning to C# is not always the best solution. Although C# can do more and most probably better then powershell, powershell is available on every system, and the editor is already shipped in Windows (VSCode is also free to download for all different OS types). the fact that C# heavily relies on Visual Studio, AND the code is compiled, makes it in my opinion, a more complex process. Because if one simple change need to be added,we need to find the sources, then to loaded into Visual studio, Edit, build etc…. whereas Powershell is just a simple text file that one can edit with notepad directly on the system.

      In powershell Classes, there are no ‘Interfaces’, abstract classes, structs or even something as private methods. We cannot even overide the getter and setters of our fields. Although I think (hope) this is just a matter of time, this limits the complexity of their usage, and can also clearly identify when we should switch to C# classes.

      As in the opposite of you, I have been looking into C# only since Classes are existing on Powershell. In some way, the OOP in PowerShell helped me to create a sort of bridge to cross over to more complex scenarios in C# which I wouldn’t have been able to tackle without the learning’s I got from PowerShell Classes. this is also one very positive point for powershell classes (Although, it doesn’t answer the question “why should I use classes in powershell”).

      Overall, I think one can write less code, and accomplish more using Powershell classes, then regular functions, without necessarily over-complicating things.

      I am curious now: What at the reasons why you would rather use c# then Powershell? (or the other way around). Do you have any concrete cases?

      Looking forward to read your anwers.


  3. Afroz January 16, 2017 at 6:10 pm - Reply

    Can methods return Custom Type that was created by using Classes? The following code is failing.


    class Human {
    [string] $Name
    $this.Name = $Name


    . “$PSScriptRoot\Human.ps1”

    [Human]::new(“Chris”) # This Works
    class Main{
    [Human] GetHumans(){ # Unable to find type [Human]
    return [Human]::new(“Chris”) # Unable to find type [Human]


    • svangulick January 16, 2017 at 7:35 pm - Reply

      Hi Afroz,

      I am not 100% I understood what you are trying to accopmlish, but perhaps there is a simpler way to get all the humans. Simply add them to an array as so:

      class Human {
      [string] $Name
      $this.Name = $Name


      $Humans = @()
      $Humans += [Human]::new(“Chris”) # This Works
      $Humans += [Human]::New(“Stephane”)


      Also, in PowerShell there is no nead for a ‘main’ class.

      • Afroz January 17, 2017 at 6:58 am - Reply

        Sorry for the confusion with the Main. Main is irrelevant. I want another class e.g RecordHolders to have a method that returns [Human] objects.

        Class RecordHolders{
        [Human] GetFastestMan(){


  4. […] A practical case for using a PowerShell Class […]

  5. JamieT November 24, 2016 at 12:40 pm - Reply

    As an it guy trying to learn this new devops world and pick up Powershell this was awesome. A few articles I have read about powershell is like reading stereo instructions in Japanese. So thanks again for something clear and understandable.

  6. alfian November 21, 2016 at 11:21 am - Reply

    I have several PS scripts (PS version 3.0)
    I would like to create class something similar to this
    class a {

    can I make it that one method actually run one script?
    Thank you

    • Stephane January 18, 2017 at 7:54 am - Reply

      Hi alfian,

      Sorry for the late reply. Absolutley you can. Convert you scripts to plain functions at first, then convert them to methods. That would be the easiedt way i think

  7. savindrasingh March 31, 2016 at 1:39 pm - Reply

    This looks similar to what we use in C#. Glad to see that it works in same fashion here. However, is there any way we can produce some DLL or EXE from this? do you know any tool or something to make EXE out of it?

    Thanks for sharing.

    • Stephane March 31, 2016 at 5:47 pm - Reply

      Hi savindrasingh,

      There are two / three options i can think of:
      Powergui (bought by dell) which is free.

      Sapiens powershell studio (not free)

      Isesteroid (not free).

      Hope this helps.

  8. William October 6, 2015 at 12:48 am - Reply

    A very good explanation of classes and related uses, I have been doing Powershell for about 2 and half years now, took up learning C# to help better understand the dotnet framework and how Powershell interacts with it, the concepts with classes are almost identical to that of C#, though Powershell seems easier to grasp.
    Great stuff with this post you have made learning this clearer, and a lot easier to conceptualize look forward to more future posts.

  9. Guido Oliveira July 17, 2015 at 9:57 pm - Reply

    Great Article Stephane! Looking forward to the next one!

    • Stephane July 17, 2015 at 11:32 pm - Reply

      Thanks mate. I am currently working on it. It will be out shortly. I’ll keep you tuned!;)

Leave a Reply

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

%d bloggers like this: