Welcome to ciysys blog

Declaring C# like Class type

Published on: 5th Dec 2019

Updated on: 16th Jan 2022


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

    # static fields
    static [int]$objCount

    # constructor
    MyObject ([string]$n){
        $this.name = $n

        # increase the number of instances that have been created.

    [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

Write-Host "instance count=$([MyObject]::objCount)"

$s = $o.ToString()
Write-Host "$s"

$j = $o | ConvertTo-Json
Write-Host $j

Use case


Jump to #POWERSHELL blog


Lau Hon Wan, software developer.