PowerShell

Creating and Using Classes in PowerShell

In this blog post, I will cover topics such as classes and objects to provide a better understanding of how PowerShell works with objects.

Classes, Objects, Properties, and Methods in PowerShell

With PowerShell 5.0 and later, PowerShell supports object‑oriented programming by allowing you to create and use classes. Classes help you structure code, model real‑world entities, and reuse logic more effectively.

What is a Class?

A class is a blueprint or template. It defines:

  • which properties (attributes) an object has
  • which methods (functions) an object can execute

What is an Object?

An object is an instance of a class.
When you create an object from a class, it contains real values for the defined properties and can execute the class methods.

Properties (Attributes)

Properties store data inside an object.
Examples: a computer name, a support number, or a status value.

Methods

Methods define actions or behavior.
They are functions inside a class that can read or modify properties or perform tasks.


Example: Creating a Class Auto (Car) in PowerShell

The following example shows how to create a simple PowerShell class and instantiate an object from it.

class Auto {
    [string]$Marke
    [string]$Modell
    [int]$Baujahr
    [int]$Leistung
    [int]$Hubraum
    [int]$Kilometerstand
    [int]$Preis
    [void] Starten() {
        Write-Host "Das Auto startet."
    }   
}

# Show classes and members (attributes + methods)
[Auto] | Get-Member -MemberType Property
[Auto].DeclaredMembers | Where-Object { $_.MemberType -eq "Property" }

# Create a Car class object
$auto1 = New-Object Auto # oder $auto1 = [Auto]::new()
$auto1.Marke = "BMW"
$auto1.Modell = "X5"
$auto1.Baujahr = 2018
$auto1.Leistung = 200
$auto1.Hubraum = 2000
$auto1.Kilometerstand = 10000
$auto1.Preis = 50000

$auto2 = [Auto]::new()
$auto2.Marke = "Audi"
$auto2.Modell = "Q7"
$auto2.Baujahr = 2019
$auto2.Leistung = 250
$auto2.Hubraum = 2500
$auto2.Kilometerstand = 5000
$auto2.Preis = 60000

$auto1
$auto1 | Get-Member
$auto1 | Get-Member -Name Marke
$auto1.GetType()
$auto1 | Select-Object -Property Marke

# Increase the price of the BMW X5 by 10%.
$auto1.Preis = $auto1.Preis * 1.1
$auto1.Preis

# Auto1 starten
$auto1.Starten()

# Show Auto1 and Auto2
$autos = @($auto1, $auto2)
$autos | Format-Table -Property Marke, Modell, Baujahr, Preis
# Alternative: 
$autos | Select-Object -Property Marke, Modell, Baujahr, Preis 

Categories: PowerShell

Tagged as: ,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.