Declaring C# like Class type

Basically, if you are familiar with C# programming language, you will find it quite straight forward to do this in Powershell.

The following sample code explains the basic of declaring class in PowerShell:

# references:
#  https://devblogs.microsoft.com/scripting/powershell-5-create-simple-class/
#  https://xainey.github.io/2016/powershell-classes-and-concepts/

# 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 instance that has 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

Comments

Popular posts from this blog

Scheduled task in Windows Task Scheduler - part 3

Create scheduled task in Windows Task Scheduler

Get all website entries in IIS