Using Classes (Creating Objects – Part 1)

by Feb 6, 2017

Beginning in PowerShell 5, there is a new keyword called “class”. It creates new classes for you. You can use classes as a blue print for new objects. Here is code that defines the blueprint for a new class called “Info”, with a number of properties:

#requires -Version 5.0
class Info 
{ 
  $Name
  $Computer
  $Date 
}

# generic syntax to create a new object instance
$infoObj = New-Object -TypeName Info

# alternate syntax PS5 or better (shorter and faster)
$infoObj = [Info]::new()
 

$infoObj

$infoObj.Name = $env:COMPUTERNAME
$infoObj.Computer = $env:COMPUTERNAME
$infoObj.Date = Get-Date

$infoObj
$infoObj.GetType().Name

You can use New-Object to create as many new instances of this class. Each instance represents a new object of type “Info” with three properties.

 
Name            Computer        Date               
----            --------        ----               
                                                   
DESKTOP-7AAMJLF DESKTOP-7AAMJLF 1/2/2017 2:00:02 PM
Info
 

This is just a very simple (yet useful) example of how to use classes to produce objects. If you just want to store different pieces of information in a new object, you could as well use [PSCustomObject] which was introduced in PowerShell 3:

#requires -Version 3.0
$infoObj = [PSCustomObject]@{
  Name = $env:COMPUTERNAME
  Computer = $env:COMPUTERNAME
  Date = Get-Date
}

$infoObj
$infoObj.GetType().Name

This approach does not use a blueprint (class) and instead creates individual new objects based on a hash table:

 
Name            Computer        Date               
----            --------        ----               
DESKTOP-7AAMJLF DESKTOP-7AAMJLF 1/2/2017 2:02:39 PM
PSCustomObject
 

So the type of the produced object is always “PSCustomObject” whereas in the previous example, the object type was defined by the class name.

Twitter This Tip! ReTweet this Tip!