Declaring C# like Class type
Published on: 5th Dec 2019
Updated on: 16th Jan 2022
Explanation
If you are familiar with C# or PHP programming language, you will find it quite straightforward to do this in Powershell.
The following sample code explains the basic of declaring class in PowerShell:
# declare a new object type - the same way like C#
class MyObject {
# instance fields
[string]$name
[string]$code
[int32]$age
# static fields
static [int]$objCount
# constructor
MyObject ([string]$n){
$this.name = $n
# increase the number of instances that have been created.
[MyObject]::objCount++;
}
[string]ToString() {
#return $this.name
return "Hello {0}!" -f $this.name
}
}
# instantiate new instance
##$o = New-Object MyObject "tester"
$o = [MyObject]::new("tester")
##$o.name = "mike"
$o.code = "m001"
$o.age = 38
#show the contents
$o
Write-Host "instance count=$([MyObject]::objCount)"
$s = $o.ToString()
Write-Host "$s"
$j = $o | ConvertTo-Json
Write-Host $j
Use case
- When you want to automate server health checks, you may want to standardize as much as possible for the data that you have collected.
- When you want to transform the data from one format to another format before sending it to an application for processing.
References
- https://devblogs.microsoft.com/scripting/powershell-5-create-simple-class/
- https://xainey.github.io/2016/powershell-classes-and-concepts/
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.