On this weblog submit, I’ll cowl subjects resembling courses and objects to offer a greater understanding of how PowerShell works with objects.
Lessons, Objects, Properties, and Strategies in PowerShell
With PowerShell 5.0 and later, PowerShell helps object‑oriented programming by permitting you to create and use courses. Lessons assist you construction code, mannequin actual‑world entities, and reuse logic extra successfully.
What’s a Class?
A class is a blueprint or template. It defines:
- which properties (attributes) an object has
- which strategies (capabilities) an object can execute
What’s an Object?
An object is an occasion of a category.
If you create an object from a category, it incorporates actual values for the outlined properties and might execute the category strategies.
Properties (Attributes)
Properties retailer information inside an object.
Examples: a pc title, a assist quantity, or a standing worth.
Strategies
Strategies outline actions or habits.
They’re capabilities inside a category that may learn or modify properties or carry out duties.
Instance: Making a Class Auto (Automotive) in PowerShell
The next instance exhibits methods to create a easy 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."
}
}
# Present courses and members (attributes + strategies)
[Auto] | Get-Member -MemberType Property
[Auto].DeclaredMembers | The place-Object { $_.MemberType -eq "Property" }
# Create a Automotive 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 -Title Marke
$auto1.GetType()
$auto1 | Choose-Object -Property Marke
# Enhance the value of the BMW X5 by 10%.
$auto1.Preis = $auto1.Preis * 1.1
$auto1.Preis
# Auto1 starten
$auto1.Starten()
# Present Auto1 and Auto2
$autos = @($auto1, $auto2)
$autos | Format-Desk -Property Marke, Modell, Baujahr, Preis
# Different:
$autos | Choose-Object -Property Marke, Modell, Baujahr, Preis
Revealed by

