Pete Hinchley: Object-Oriented PowerShell without PowerShell 5.0

PowerShell 5.0 introduces support for object-oriented programming, however, we don't always have the luxury of working on systems where PowerShell 5.0 is installed. When I am stuck using an older version of PowerShell, and I feel the need to write object-oriented code, I use the following approach:

function builder() {
  $instance = new-object psobject

  $instance | add-member -membertype scriptmethod -name property -value {
    param($name, $value)
    $this | add-member -membertype noteproperty -name $name -value $value -force

  $instance | add-member -membertype scriptmethod -name method -value {
    param($name, $block)
    $this | add-member -membertype scriptmethod -name $name -value $block -force

  return $instance

function person {

  $obj = builder

  $"name", $name)

  $obj.method("greet", {
    return "{0} {1}." -f $message, $

  return $obj

$pete = person "Pete"
$sara = person "Sara"


The output of the code is:

Hi Pete.
Hello Sara.

Even inheritance is simple:

function boy {

  $obj = person $name
  $"gender", 'male')
  return $obj

$fred = boy "Fred"

The output is: