Member-only story
PowerShell Class — A Use Case For The Printers
PowerShell Class is a not-very-well-known hidden gem among the admins. It’s not perfect, but the benefits are obvious when you find a place to adapt it.
Intro
Yes, PowerShell has been capable of defining classes since version 5.1, which was released on August 2nd, 2016, seven years ago!
Although classes are a fundamental aspect of all object-oriented programming languages, PowerShell is a “late adopter” in this regard, so many people may not be familiar with this feature or have even heard of it.
In my recent side project, I had the opportunity to work with PowerShell classes, and I found it to be both challenging and enjoyable.
By creating objects with rich attributes and powerful methods, I was able to take full control of the code I was writing. I’d like to share my experience with PowerShell classes with others.
How does Class work in PowerShell?
Defining a PowerShell Class:
class Animal {
# Attributes
[string]$Name
[string]$Species
# Constructor
Animal([string]$Name, [string]$Species) {
$this.Name = $Name
$this.Species = $Species
}
# Method
[string]whoami() {
return "$($this.Name) is a $($this.Species)"
}
}
Using it:
# Calling it
$dog = [Animal]::new("BoBo","Hasky")
$dog.whoami()
# Output
"BoBo is a…