How to Create Custom Objects in PowerShell?

Do you want to know about custom objects in PowerShell? In this tutorial, I will explain how to create custom objects in PowerShell. Keep reading it. I have explained with practical examples.

Custom Objects in PowerShell

Custom objects in PowerShell allow you to structure your data in a way that makes it easier to manipulate, display, and export. They are particularly useful when dealing with complex datasets or when you need to pass structured data between different parts of a script.

Here are some benefits of using custom objects in PowerShell.

  1. Improved Data Organization: Custom objects enable you to organize data into named properties, making it easier to understand and work with.
  2. Enhanced Script Readability: By using custom objects, you can make your scripts more readable and maintainable.
  3. Ease of Data Manipulation: Custom objects allow for more straightforward data manipulation and filtering using PowerShell cmdlets.

Read Create a Credential Object in PowerShell

Create Custom Objects in PowerShell

Now, let me show you how to create custom objects in PowerShell using different methods.

Basic Syntax

To create a custom object in PowerShell, you can use the New-Object cmdlet or the PSCustomObject type accelerator. Here’s a simple example using New-Object:

$person = New-Object PSObject -Property @{
    FirstName = 'John'
    LastName  = 'Doe'
    Age       = 30
    City      = 'New York'
}

This code creates a custom object representing a person with properties for FirstName, LastName, Age, and City.

Using PSCustomObject

The PSCustomObject type accelerator is a more concise and preferred method for creating custom objects in PowerShell. Here is the same example using PSCustomObject:

$person = [PSCustomObject]@{
    FirstName = 'John'
    LastName  = 'Doe'
    Age       = 30
    City      = 'New York'
}

Adding Methods to Custom Objects

Custom objects in PowerShell can also include methods. Methods are functions attached to objects that can perform actions using the object’s data. Here’s an example of adding a method to our person object:

$person = [PSCustomObject]@{
    FirstName = 'John'
    LastName  = 'Doe'
    Age       = 30
    City      = 'New York'
}

$person | Add-Member -MemberType ScriptMethod -Name 'GetFullName' -Value {
    return "$($this.FirstName) $($this.LastName)"
}

# Using the method
$person.GetFullName()

Here is the exact output in the screenshot below:

Create Custom Objects in PowerShell

Adding Calculated Properties to Custom Objects

You can add calculated properties to custom objects. For example, suppose you want to add a property that calculates the full name of each employee:

$employees | ForEach-Object {
    $_ | Add-Member -MemberType NoteProperty -Name 'FullName' -Value "$($_.FirstName) $($_.LastName)"
}

$employees | Format-Table -Property FullName, Age, Department, City

Read Create Objects in PowerShell

Filtering and Sorting PowerShell Custom Objects

PowerShell makes it easy to filter and sort custom objects. For example, to find employees in the IT department and sort them by age:

$itEmployees = $employees | Where-Object { $_.Department -eq 'IT' } | Sort-Object -Property Age
$itEmployees | Format-Table -Property FirstName, LastName, Age, Department, City

Export Custom Objects in PowerShelll

Custom objects can be exported to various formats such as CSV, JSON, or XML for further processing or reporting.

Here, I will show you how to export custom objects to CSV and to JSON using PowerShell.

Exporting to CSV

To export the employee data to a CSV file:

$employees | Export-Csv -Path 'C:\Employees.csv' -NoTypeInformation

Exporting to JSON

To export the employee data to a JSON file:

$employees | ConvertTo-Json | Set-Content -Path 'C:\Employees.json'

Read PowerShell Sort-Object

Handle Complex Data Structures in PowerShell

Custom objects in PowerShell can also handle more complex data structures, such as nested objects. For example, if each employee has a list of projects:

$employee1 = [PSCustomObject]@{
    FirstName = 'Alice'
    LastName  = 'Johnson'
    Age       = 28
    Department = 'Sales'
    City      = 'Chicago'
    Projects  = @(
        [PSCustomObject]@{ Name = 'Project A'; Deadline = '2024-12-01' },
        [PSCustomObject]@{ Name = 'Project B'; Deadline = '2025-01-15' }
    )
}

$employee2 = [PSCustomObject]@{
    FirstName = 'Bob'
    LastName  = 'Smith'
    Age       = 34
    Department = 'IT'
    City      = 'San Francisco'
    Projects  = @(
        [PSCustomObject]@{ Name = 'Project X'; Deadline = '2024-11-30' },
        [PSCustomObject]@{ Name = 'Project Y'; Deadline = '2025-02-20' }
    )
}

$employees = @($employee1, $employee2)

Accessing Nested Data

To access nested data, such as the projects of each employee, you can use a loop:

foreach ($employee in $employees) {
    Write-Output "Employee: $($employee.FirstName) $($employee.LastName)"
    foreach ($project in $employee.Projects) {
        Write-Output "  Project: $($project.Name), Deadline: $($project.Deadline)"
    }
}

Here is the exact output in the screenshot below:

How to Create Custom Objects in PowerShell

Read PowerShell Compare-Object

Custom Objects in PowerShell Example: Managing Employee Data

Let’s consider a real-world scenario where you need to manage employee data for a company based in the USA. You want to create a custom object for each employee and then compile these into a list for easy management.

Step 1: Create Employee Objects

First, create a custom object for each employee:

$employee1 = [PSCustomObject]@{
    FirstName = 'Alice'
    LastName  = 'Johnson'
    Age       = 28
    Department = 'Sales'
    City      = 'Chicago'
}

$employee2 = [PSCustomObject]@{
    FirstName = 'Bob'
    LastName  = 'Smith'
    Age       = 34
    Department = 'IT'
    City      = 'San Francisco'
}

Step 2: Compile Employee Objects into a List

Next, compile these objects into a list (array) for easy management:

$employees = @($employee1, $employee2)

Step 3: Display Employee Data

You can now easily display the employee data using PowerShell’s Format-Table cmdlet:

$employees | Format-Table -Property FirstName, LastName, Age, Department, City

Conclusion

In this tutorial, I explained about custom objects in PowerShell. I also explained how to create custom objects in PowerShell using different methods.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.