TExcelTAD
Home › PowerShell › PowerShell Classes & Enums

PowerShell Classes & Enums

Since PowerShell 5, you can define your own classes and enums. A class is a blueprint for objects with typed properties, constructors and methods; an enum is a fixed set of named values. For most scripts [pscustomobject] is enough, but classes shine when you need validation, behaviour (methods), inheritance or a reusable type.

Enums

An enum gives names to a set of allowed values. A variable or parameter of that type accepts only those names:

powershell · try it yourself
enum Severity {
    Low = 1
    Medium = 2
    High = 3
    Critical = 4
}

$level = [Severity]::High
$level
[int]$level
[Severity]'medium'
$level -gt [Severity]::Medium
[enum]::GetNames([Severity]) -join ', '

try { [Severity]'Extreme' } catch { 'Not a valid Severity' }
High
3
Medium
True
Low, Medium, High, Critical
Not a valid Severity

Enums can be compared and sorted by their underlying number, and they give tab completion for parameters typed with them.

Flags enums

With the [Flags()] attribute and powers of two, one value can hold several options at once:

powershell · try it yourself
[Flags()] enum Permission {
    None    = 0
    Read    = 1
    Write   = 2
    Execute = 4
}

$p = [Permission]::Read -bor [Permission]::Write
$p
$p.HasFlag([Permission]::Write)
$p.HasFlag([Permission]::Execute)
[int]$p
Read, Write
True
False
3

Defining a class

A class has properties (typed fields), optional constructors (methods named like the class) and methods. Inside the class, $this refers to the current object, and methods must declare their return type and use return:

powershell · try it yourself
class BankAccount {
    [string]$Owner
    [decimal]$Balance = 0
    hidden [System.Collections.Generic.List[string]]$Log = @()

    BankAccount([string]$owner) {
        $this.Owner = $owner
    }

    [void] Deposit([decimal]$amount) {
        if ($amount -le 0) { throw 'Deposit must be positive' }
        $this.Balance += $amount
        $this.Log.Add("deposit $amount")
    }

    [bool] Withdraw([decimal]$amount) {
        if ($amount -gt $this.Balance) { return $false }
        $this.Balance -= $amount
        $this.Log.Add("withdraw $amount")
        return $true
    }

    [string] ToString() {
        return '{0}: {1:N2}' -f $this.Owner, $this.Balance
    }
}

$acct = [BankAccount]::new('Ada')
$acct.Deposit(150)
$acct.Withdraw(40)
$acct.Withdraw(500)
$acct.ToString()
$acct.Log -join '; '
try { $acct.Deposit(-5) } catch { "Error: $($_.Exception.Message)" }
True
False
Ada: 110.00
deposit 150; withdraw 40
Error: Deposit must be positive

Unlike functions, class methods only output what they return; stray values don't leak. hidden keeps a member out of default display and tab completion.

Static members and validation

static members belong to the class itself, not to an object. Property attributes such as [ValidateRange()] work in classes, too:

powershell · try it yourself
class Temperature {
    [ValidateRange(-273.15, 10000)]
    [double]$Celsius

    Temperature([double]$c) { $this.Celsius = $c }

    static [Temperature] FromFahrenheit([double]$f) {
        return [Temperature]::new(($f - 32) * 5 / 9)
    }

    [double] Fahrenheit() { return $this.Celsius * 9 / 5 + 32 }
}

$t = [Temperature]::FromFahrenheit(212)
$t.Celsius
[Temperature]::new(25).Fahrenheit()
try { [Temperature]::new(-300) } catch { 'Below absolute zero is not allowed' }
100
77
Below absolute zero is not allowed

Inheritance

A class can inherit from another with :. It gets all members of the base class and can override methods. Call the base constructor with : base(...):

powershell · try it yourself
class Shape {
    [string]$Name
    Shape([string]$name) { $this.Name = $name }
    [double] Area() { return 0 }
    [string] Describe() { return '{0} with area {1:N2}' -f $this.Name, $this.Area() }
}

class Circle : Shape {
    [double]$Radius
    Circle([double]$r) : base('circle') { $this.Radius = $r }
    [double] Area() { return [math]::PI * $this.Radius * $this.Radius }
}

class Rectangle : Shape {
    [double]$Width; [double]$Height
    Rectangle([double]$w, [double]$h) : base('rectangle') { $this.Width = $w; $this.Height = $h }
    [double] Area() { return $this.Width * $this.Height }
}

$shapes = [Shape[]]@([Circle]::new(1), [Rectangle]::new(3, 4), [Circle]::new(2.5))
$shapes | ForEach-Object { $_.Describe() }
($shapes | Sort-Object { $_.Area() } -Descending | Select-Object -First 1).Name
$shapes[0] -is [Shape]
circle with area 3.14
rectangle with area 12.00
circle with area 19.63
circle
True

Classes vs PSCustomObject

Use Choose
Quick records to display or export [pscustomobject]
Type checks, validation, methods class
Fixed set of options enum
Sharing types between scripts class in a module, loaded with using module

Note: A class defined in a module is only visible to scripts that load it with using module ./MyModule.psm1 at the very top, not with Import-Module. And once a class is loaded into a session, it can't be redefined until you start a new session.

Test yourself

Inside a class method, how do you refer to the object's own properties?

  1. $self
  2. $this
  3. $_
  4. $PSItem

What does a class method with return type [int] output if it contains a stray line 'debug' before return 5?

  1. 'debug' and 5
  2. Only 5
  3. Only 'debug'
  4. An error

How do you create an instance of class Server with a constructor taking a name?

  1. New-Server 'web01'
  2. [Server]::new('web01')
  3. Server('web01')
  4. $Server.Create('web01')