Skip to content
AgileLogics
6 min read

Classes

PowerShell 5 and later support classes — types with properties, methods, constructors, and inheritance.

class BankAccount {
  [string]$Owner
  hidden [decimal]$Balance = 0

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

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

  [decimal] GetBalance() {
    return $this.Balance
  }

  [string] ToString() {
    return "$($this.Owner): $($this.Balance)"
  }
}

$account = [BankAccount]::new('Ada')
$account.Deposit(150)
$account.Deposit(25.5)
$account.GetBalance()
"$account"
try { $account.Deposit(-5) } catch { $_.Exception.Message }
175.5
Ada: 175.5
Deposit must be positive
  • Properties have types; hidden keeps a property out of default display and tab completion (it isn't truly private).
  • A constructor has the class's name. Create objects with [ClassName]::new(...).
  • Methods declare a return type ([void] for none) and must use return explicitly — unlike functions, stray values are not output.
  • Inside the class, use $this to reach its members.

Inheritance

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 Square : Shape {
  [double]$Side
  Square([double]$s) : base('Square') { $this.Side = $s }
  [double] Area() { return $this.Side * $this.Side }
}

$shapes = [Circle]::new(1), [Square]::new(3)
$shapes | ForEach-Object { $_.Describe() }
Circle with area 3.14
Square with area 9.00

: base(...) calls the parent constructor; overriding Area() changes behavior while Describe() is inherited.

Enums

enum Severity { Low = 1; Medium = 2; High = 3; Critical = 4 }

$level = [Severity]::High
$level
[int]$level
$level -gt [Severity]::Medium
[Severity]'critical'
[Enum]::GetNames([Severity]) -join ', '
High
3
True
Critical
Low, Medium, High, Critical

An enum used as a parameter type gives validation and tab completion for free — like ValidateSet, but reusable.

When to use classes

Classes shine for modeling domain objects with behavior, for DSC resources, and for custom validation or argument-completion attributes. For plain data output, [pscustomobject] is still simpler. Note that a class defined in a module is only visible to scripts that load it with using module ModuleName, not Import-Module.