Search notes:

PowerShell: Classes

The class keyword allows to define user defined types.

Simple demonstration of basic features

The following simple example tries to demonstrate the most important and basic features of a user-defined class:

Class definition

The definition of a class named CLS:
set-strictMode -version latest

class CLS {
 #
 #   The class's member variables:
 #
  [int   ] $num
  [string] $txt

  static [int] $accumulator = 42

 #
 #   The class's constructor:
 #
   CLS($n, $t) {
     $this.num = $n
     $this.txt = $t
   }

 #
 #   A member method that returns a string.
 #
  [string] combineNumAndTxt() {
     return "$($this.num) - $($this.txt)"
  }

 #
 #   A member method that doesn't return
 #   a value. It's «return type» can be
 #   explicitely specified as void:
 #
  [void] printMembers() {
     write-host $this.combineNumAndTxt()
  }

 #
 #   A static method
 #
  static [Int] add($x) {
     [CLS]::accumulator += $x
     return [CLS]::accumulator
  }
}

Creating an instance

An instance of a class is created with the new-object cmdlet or by using the static method call syntax and the method name new:
$obj        =            [CLS]::new(42, 'hello world')
$anotherObj = new-object  CLS       99, 'ninety-nine'

Call methods

A method is called using the object variable followed by a dot and the name of the method:
write-host "obj.num = $($obj.num), obj.txt = $($obj.txt)"
#
#    obj.num = 42, obj.txt = hello world

write-host $obj.combineNumAndTxt()
#
#    42 - hello world

$obj.printMembers()
#
#    42 - hello world

Call a static method

A static method is called by putting the class name into square brackets, followed by two colons, followed by the name of the method:
#
# Invoke a static method
#
[CLS]::add(57)
#
#    99

Show type name

$obj.GetType().FullName
#
#    CLS

$obj.GetType().BaseType.FullName
#
#    System.Object

See also

Class methods
Inheritance
Classes with and without an explicit ToString() method
This PowerShell example that demonstrates how a PowerShell class implements System.IComparable and overrides Equals() and GetHashCode() in order to be comparable with -eq, -gt, -lt etc..

Index