Using PowerShell Classes 2

by Jul 6, 2017

Starting in PowerShell 5, you can define PowerShell classes. You can use classes to create new objects, and by defining one or more “constructors”, you can easily initialize the newly created objects as well.

Let’s have a look:

class Employee
{
    [int]$Id
    [string]$Name

    Employee([int]$Id, [string]$Name)
    {
        $this.Id = $Id
        $this.Name = $Name
    }
    Employee ([string]$Name)
    {
        $this.Id = -1
        $this.Name = $Name
    }
    Employee ()
    {
        $this.Id = -1
        $this.Name = 'Undefined'
    }
}

Once you run this code, there is a new class called “Employee” with three constructors. And here is how you can use the new class:

 
PS> [Employee]::new()

Id Name     
-- ----     
-1 Undefined



PS> [Employee]::new('Tobias')

Id Name  
-- ----  
-1 Tobias



PS> [Employee]::new(999, 'Tobias')

 Id Name  
 -- ----  
999 Tobias



PS> 
 

Each call is using a different constructor, and the class creates and initializes new objects for you accordingly.

Twitter This Tip! ReTweet this Tip!