2 min read

PowerShell Classes

PowerShell 5.0 introduced a formal syntax for defining classes and other user-defined types, bringing object-oriented programming (OOP) concepts directly into the language.

Parent Topic: PowerShell Scripting and Programming Related: PowerShell Comprehensive Guide

1. Defining a Class

A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods).

class Computer {
    # Properties
    [string]$Hostname
    [string]$OperatingSystem
    [int]$RamGB

    # Methods
    [string] GetStatus() {
        return "Computer '$($this.Hostname)' is running $($this.OperatingSystem)."
    }
}

Instantiating a Class

You create an "instance" of a class using [ClassName]::new() or New-Object.

$server = [Computer]::new()
$server.Hostname = "SRV01"
$server.OperatingSystem = "Windows Server 2022"
$server.RamGB = 64

$server.GetStatus()
# Output: Computer 'SRV01' is running Windows Server 2022.

2. Constructors

Constructors are special methods that run when a new object is created, allowing you to initialize its properties.

class Server {
    [string]$Hostname
    [string]$IPAddress

    # Default constructor
    Server() {
        $this.Hostname = "localhost"
        $this.IPAddress = "127.0.0.1"
    }

    # Overloaded constructor with parameters
    Server([string]$Hostname, [string]$IPAddress) {
        $this.Hostname = $Hostname
        $this.IPAddress = $IPAddress
    }
}

$defaultSrv = [Server]::new()
$customSrv = [Server]::new("WEB01", "192.168.1.10")

3. Inheritance

Inheritance allows a class to inherit properties and methods from a "base" class. This promotes code reuse.

class VirtualMachine : Computer {
    # Inherits Hostname, OperatingSystem, RamGB, and GetStatus() from Computer

    # New property specific to VirtualMachine
    [string]$Hypervisor

    # Overriding a method
    [string] GetStatus() {
        # Call the parent method and add to it
        $parentStatus = [super]::GetStatus()
        return "$parentStatus on hypervisor $($this.Hypervisor)."
    }
}

$vm = [VirtualMachine]::new()
$vm.Hostname = "VM-TEST01"
$vm.OperatingSystem = "Ubuntu 24.04"
$vm.Hypervisor = "Hyper-V"

$vm.GetStatus()
# Output: Computer 'VM-TEST01' is running Ubuntu 24.04. on hypervisor Hyper-V.
  • [super]::GetStatus(): This syntax allows you to call the method from the parent class.

4. Static Properties and Methods

Static members belong to the class itself, not to an instance of the class. You access them using [ClassName]::Member.

class Logger {
    static [string]$LogPath = "C:\Logs\app.log"

    static [void] Write([string]$Message) {
        $timestamp = Get-Date
        Add-Content -Path [Logger]::LogPath -Value "[$timestamp] - $Message"
    }
}

# No instance needed
[Logger]::Write("Application started.")

Return to PowerShell Scripting and Programming