Now that we are familiar with what an object is, what it’s made up of – properties and methods – and how we can work with them, it’s time to create our own objects!
To create an object, we use the New-Object
cmdlet like so:
$dog = New-Object -TypeName PSCustomObject
The -TypeName PSCustomObject
means the object has the type of PSCustomObject
, a class used for creating custom objects.
By default, the new dog
custom object has no properties and four methods.
Adding Properties
With the object created, we can now use the Add-Member
cmdlet to add methods and properties. We must specify the type of member we wish to add.
In the case of a property with key-value pair, we use a NoteProperty
. Consider the example below.
$dog | Add-Member -MemberType NoteProperty -Name "Name" -Value "Rufus" $dog | Add-Member -MemberType NoteProperty -Name "Age" -Value 10
Our custom dog
object now has two properties:
Name
with the string value ofRufus
Age
with the integer value of10
Adding Methods
The syntax for adding a method is very similar to that of properties. However, for the MemberType
parameter, we use ScriptMethod
.
$dog | Add-Member -MemberType ScriptMethod -Name "speak" -Value { Write-Host "Woof!"}
Just like a property, we name the method "speak"
using -Name
. For -Value
we enclose a line of code, which outputs the string Woof!
.
Now we can use the newly created method:
$dog.speak() # outputs: Woof!
Instructions
In the greet.ps1 file, create a custom object named $person
using the New-Object
cmdlet.
Click Run to go to the next checkpoint.
Use Add-Member
cmdlet to add a property to the $person
object called FirstName
with your name as its string value.
Click Run to move on.
Now add a method to the $person
object. Name the method "greeting"
and have the enclosed line of code output a greeting string using Write-Host
Click Run to continue.
Call the newly-added .greeting()
method of the $person
object.
Click Run to output the greeting.