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 {
param($name)
$obj = builder
$obj.property("name", $name)
$obj.method("greet", {
param($message)
return "{0} {1}." -f $message, $this.name
})
return $obj
}
$pete = person "Pete"
$sara = person "Sara"
$pete.greet("Hi")
$sara.greet("Hello")
The output of the code is:
Hi Pete.
Hello Sara.
Even inheritance is simple:
function boy {
param($name)
$obj = person $name
$obj.property("gender", 'male')
return $obj
}
$fred = boy "Fred"
$fred.gender
The output is:
male