PowerShell v5 class method – problems


Playing with the new class function in PowerShell v5, and I’m trying to get my head around if we can put methods into classes.

I’ve tried the below and played about with it for a bit, but haven’t been having luck.

I’ve tried with manually entering a computer name via setting the property, but then I assumed you’d need it at object creation

Exceptions I’m getting are

Full exception link from $error is on http://pastebin.com/WtxfYzb5

Got a bit further used $this.prop, but you cant initiate the constructor with your own parameters.


What you’re needing is a constructor (or multiple constructors), if you don’t specify one within your class the only constructor you get is the default one with no arguments.

As summing you’re wanting to initialize your Server with an ip address different from the default (and allowing the default for $ping to fire.)

I’ve included the regions I normally include in my classes to distinguish between properties, constructors and methods.

Now you can create an object without passing a parameter to it:

You can now also supply a ip address (or server name) when creating the object (note, don’t supply the property name.)

Of note, notice there are two constructors inside the class. When testing this the default constructor that takes no arguments was no longer valid once I specified one of my own, so I’ve included a zero argument constructor for when you want to use all default values.

For more info about these classes, their constructors and methods, I would recommend checking out the videos Trevor Sullivan has released in the last few days.


PowerShell v5 class method – problems by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply