BudiBadu Logo
Samplebadu

PowerShell by Example: Classes and Enums

PowerShell 7

Implementing object-oriented programming with this code example demonstrating class definition with typed properties, constructors, methods, inheritance, and enumerations for structured data types.

Code

# Define an Enum
enum ServerRole {
    Web
    Database
    Cache
}

# Define a Base Class
class BaseServer {
    [string]$Hostname
    [string]$IPAddress
    [bool]$IsActive

    # Constructor
    BaseServer([string]$name, [string]$ip) {
        $this.Hostname = $name
        $this.IPAddress = $ip
        $this.IsActive = $true
    }

    # Method
    [string] GetStatus() {
        return "$($this.Hostname) is $(if ($this.IsActive) {'Up'} else {'Down'})"
    }
}

# Inheritance
class AppServer : BaseServer {
    [ServerRole]$Role
    [int]$Port

    # Constructor calling base
    AppServer([string]$name, [string]$ip, [ServerRole]$role) : base($name, $ip) {
        $this.Role = $role
        $this.Port = 8080
    }

    # Method Overload
    [void] Restart([int]$delaySeconds) {
        Write-Host "Restarting $($this.Hostname) in $delaySeconds seconds..."
    }
}

# Usage
$web1 = [AppServer]::new("web-01", "10.0.0.5", [ServerRole]::Web)
Write-Host $web1.GetStatus()
$web1.Restart(30)

Explanation

PowerShell 5.0 introduced formal support for classes and enumerations, bringing robust object-oriented programming capabilities directly to the scripting language. The class keyword defines a blueprint for objects, encapsulating data in properties and behavior in methods. Unlike PSCustomObject which is dynamic and loosely typed, classes provide strict typing, inheritance, and polymorphism, making them ideal for complex data modeling, DSC resources, and structured module development. Properties are strongly typed, and methods can define return types and input parameters, enforcing a contract that improves code reliability and tooling support.

Constructors are special methods that initialize new object instances, defined with the same name as the class. They can be overloaded to provide multiple initialization strategies. Inheritance, denoted by the : BaseClass syntax, allows a child class to inherit properties and methods from a parent class, promoting code reuse. The base keyword allows the child class constructor to invoke the parent's constructor, ensuring proper initialization of the inherited state. This hierarchical structure enables developers to build sophisticated object models that mirror real-world relationships.

Enumerations, defined with the enum keyword, create a distinct type consisting of a set of named constants. Enums improve code readability and maintainability by replacing magic numbers or string literals with meaningful identifiers. They are strongly typed, preventing invalid values from being assigned to variables or properties constrained to that enum type. Together, classes and enums elevate PowerShell from a simple scripting tool to a language capable of handling enterprise-grade automation architectures and complex software design patterns.

  • Use class for structured data and strict typing
  • Implement enum to replace magic strings and numbers
  • Leverage inheritance for code reuse and polymorphism
  • Define constructors for controlled object initialization

Code Breakdown

2
enum keyword defines a set of named constants for type safety.
9
class keyword defines a blueprint with typed properties and methods.
15
$this variable refers to the current instance of the class object.
28
: BaseServer syntax establishes inheritance from a parent class.
33
: base() calls the parent class constructor during initialization.