How to create an object of a class in PowerShell
PowerShell supports Object-Oriented Programming (OOP). This means we can define classes and instantiate objects of those classes to use in our code.
Before we can instantiate objects, we need to define a class.
Defining a class
A class is a user-defined type created with the keyword class followed by its specified name. It may contain attributes that represent various properties of the class and methods used to give the class functionality.
Let’s start by creating a class Hero, which defines a superhero with several properties.
class Hero {
[string]$realName
[string]$heroName
[string]$superPower
[int32]$age
}
We have successfully defined the class. Now, we move towards giving our class some functionality by creating methods.
Creating methods
We will be creating a printDetails() function that will print the details of the hero. Then, we will define the constructors for our class.
class Hero {
[string]$realName
[string]$heroName
[string]$superPower
[int32]$age
Hero () {} # default constructor
# overloaded constructor
Hero ([string]$realName, [string]$heroName, [string]$superPower, [int32]$age)
{
$this.realName = $realName
$this.heroName = $heroName
$this.superPower = $superPower
$this.age = $age
}
[string] printDetails () # class method returning type string
{
return "$this.realName $this.heroName $this.age $this.superPower"
}
}
Our class is now complete. We have defined both a default constructor and an overloaded constructor. We have also defined the printDetails() method that prints the hero’s details, separated by a space.
Note: Methods in PowerShell must
returnsomething.
Instantiating objects
We now move to the final phase: instantiating and using our Hero class object.
There are various ways of instantiating objects in PowerShell. We will be discussing the following:
- The
New-Objectcmdlet - The
new()default method
The New-Object cmdlet
New-Object is a keyword in PowerShell. The following is the syntax for instantiating an object using New-Object.
New-Object -Typename <ClassName> -ArgumentList <Constructor>
Specifically, for our Hero class, we use the overloaded constructor, and this becomes:
$myHero = New-Object -TypeName Hero -ArgumentList 'Bruce Banner', 'Hulk', 'Smash', 35
To use the default constructor, simply remove the ArgumentList.
The new() method
new() is a static method defined by default in every user-defined class. The following is the syntax for instantiating an object using the new() method.
[<ClassName>]::new(<Constructor>)
Specifically, for our Hero class, when we use the overloaded constructor, this becomes:
$myHero = [Hero]::new('Bruce Banner', 'Hulk', 'Smash', 35)
Using the same function without parameters will invoke the default constructor.
Finally, let’s use our instantiated object to call the printDetails() function.
$myHero = [Hero]::new('Bruce Banner', 'Hulk', 'Smash', 35)
$myhero.printDetails()
Output
Bruce Banner Hulk 35 Smash
Free Resources