Learn

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.

Screenshot of a PowerShell terminal in which Get-Member cmdlet is run on the dog object. The output shows four pre-defined methods.

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:

  1. Name with the string value of Rufus
  2. Age with the integer value of 10
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!.

Screenshot of a PowerShell terminal in which Get-Member cmdlet is run on the dog object. This time, the output includes 2 Note Properties and the speak ScriptMethod. When the speak method is called, the output displays "Woof!".

Now we can use the newly created method:

$dog.speak() # outputs: Woof!

Instructions

1.

In the greet.ps1 file, create a custom object named $person using the New-Object cmdlet.

Click Run to go to the next checkpoint.

2.

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.

3.

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.

4.

Call the newly-added .greeting() method of the $person object.

Click Run to output the greeting.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?