# Unlocking PowerShell Magic: Different Approach to Creating ‘Empty’ PSCustomObjects

Today I saw an article from Christian Ritter, “PowerShell: Creating an “empty” PSCustomObject” on X that got me curious. Do people create empty objects like Christian proposes? I want to offer an alternative to Christian’s article, which uses OrderedDictionary and converts to PSCustomObject.

blog

10 Aug 2023 es

![Unlocking PowerShell Magic: Different Approach to Creating ‘Empty’ PSCustomObjects](/wp-content/uploads/2023/08/UnlockingPowerShellMagic.png)

[Ver imágenes (2)](#pf-content-image-1-0)

Today I saw an article from Christian Ritter, [“PowerShell: Creating an “empty” PSCustomObject”](https://hcritter.devdojo.com/powershell-creating-an-empty-pscustomobject) on X that got me curious. Do people create empty objects like Christian proposes? I want to offer an alternative to Christian's article, which uses **OrderedDictionary** and converts to **PSCustomObject**.

### 💡 Converting OrderedDictionary to PSCustomObject

Here's a snippet code that shows how to create a custom object using OrderedDictionary and conversion process

```powershell
$CustomObject = [ordered] @{}
$CustomObject['FirstName'] = 'John'
$CustomObject['LastName'] = 'Doe'
$CustomObject['UserName'] = 'John.Doe'
[pscustomobject] $CustomObject
```

You can also create custom objects **dynamically** using a similar approach to what Christian proposed.

```powershell
$propertyDefinitions = @{
    Users   = @(
        "FirstName", "LastName", "UserName", "Title", "Department",
        "StreetAddress", "City", "State", "PostalCode", "Country",
        "PhoneNumber", "MobilePhone", "UsageLocation", "License"
    )
    Groups  = @(
        "DisplayName", "PrimarySMTP", "Description", "Owner", "Type"
    )
    JobRole = @(
        "DisplayName", "PrimarySMTP", "Description", "Type"
    )
}


$CustomObject2 = [ordered] @{}
foreach ($P in $propertyDefinitions.Users) {
    $CustomObject2[$P] = $null
}
[PSCustomObject] $CustomObject2

$CustomObject3 = [ordered] @{}
foreach ($P in $propertyDefinitions.Groups) {
    $CustomObject3[$P] = $null
}
[PSCustomObject] $CustomObject3

$CustomObject4 = [ordered] @{}
foreach ($P in $propertyDefinitions.JobRole) {
    $CustomObject4[$P] = $null
}
[PSCustomObject] $CustomObject4
```

**OrderedDictionary** additionally offers the ability to create an object with some data and then append data on the fly in your script. This means, for example, you could create a dictionary first at the beginning of the script, and during the whole run of the script, you could append data to it without ever pre-creating it in the first place, to finally convert it to a custom object.

```powershell
$Properties = 'Title', 'Department', 'State'
$CustomObject1 = [ordered] @{
    Name = 'John'
    Age  = 30
    City = 'New York'
}
foreach ($P in $Properties) {
    $CustomObject1[$P] = $null
}
[pscustomobject] $CustomObject1
```

In a long script you could do

```powershell
$CustomObject1 = [ordered] @{
    Name = 'John'
    Age  = 30
    City = 'New York'
}

$CustomObject1['Address'] = 'New Value'

$CustomObject1['State'] = 'New Value 2'
# Convert to PSCustomObject
[pscustomobject] $CustomObject1
```

Another benefit of using **OrderedDictionary** is that you can add to it inside other functions without ever having to destroy the object, overwrite it, or even knowing beforehand what it will look like.

```powershell
function Add-Values {
    [CmdletBinding()]
    param(
        [System.Collections.IDictionary] $Dictionary,
        [string] $Key,
        [object] $Value
    )
    $Dictionary[$Key] = $Value
}

$CustomObject1 = [ordered] @{
    Name = 'John'
    Age  = 30
    City = 'New York'
}

$CustomObject1['Address'] = 'New Value'

$CustomObject1['State'] = 'New Value 2'
Add-Values -Dictionary $CustomObject1 -Key 'ZipCode' -Value 'New Value 3'

Add-Values -Dictionary $CustomObject1 -Key 'EmployeeID' -Value 'New Value 4'

# Convert to PSCustomObject
[pscustomobject] $CustomObject1
```

I hope this short blog post will help you decide between my and Christian solutions. Both solutions have their own strengths, and depending on who likes what, you may end up using one or the other. Christian solution is based on **PowerShell 2.0** when it was the only way to create PSCustomObject.

```powershell
# what Christian proposes
$customObject1 = [PSCustomObject]@{} # this line is actually not needed
$customObject1 | Select-Object -Property $PropertyNames

# Idential, with just one line of code, as Select-Object creates new object on the fly
'' | Select-Object -Property $PropertyNames
```

I was curious if there's any performance difference between those two solutions. Using a simple **Measure-Command** gives us the answer.

```powershell
$PropertyNames = @(
    "FirstName", "LastName", "UserName", "Title", "Department",
    "StreetAddress", "City", "State", "PostalCode", "Country",
    "PhoneNumber", "MobilePhone", "UsageLocation", "License"
)

Measure-Command {
    for ($i = 0; $i -lt 100000; $i++) {
        $CustomObject1 = [ordered] @{}
        foreach ($P in $PropertyNames) {
            $CustomObject1[$P] = $null
        }
        $T = [pscustomobject] $CustomObject1
    }
}

Measure-Command {
    for ($i = 0; $i -lt 100000; $i++) {
       $T2 = '' | Select-Object -Property $PropertyNames
    }
}
```

In PowerShell 5.1, over 100k iterations, it takes about 1 second less for my approach than using Select-Object.

[!\[PowerShell 5.1 benchmark comparing an OrderedDictionary PSCustomObject approach against Select-Object for 100000 iterations.\](/wp-content/uploads/2023/08/img_64d4a85ba0208.png)](/wp-content/uploads/2023/08/img_64d4a85ba0208.png)

In PowerShell 7, the difference is about 500ms which is not noticeable.

[!\[PowerShell 7.3 benchmark comparing an OrderedDictionary PSCustomObject approach against Select-Object for 100000 iterations.\](/wp-content/uploads/2023/08/img_64d4a8802adb3.png)](/wp-content/uploads/2023/08/img_64d4a8802adb3.png)

To summarize, both solutions work; I believe **OrderedDictionary** conversion has more pros and, at least for me, is easier to read and understand how everything happens. Just a thing of note – you could also use Hashtable instead of **OrderedDictionary**, but then the order of properties is not guaranteed, which may or may not matter to you. In the end, the choice is always yours. Enjoy

## Proyectos relacionados

Proyectos que encajan con las etiquetas, categorías y contenido de este artículo.

[Todos los proyectos](/es/proyectos/)

Buscando proyectos relacionados...

[Volver al blog](/blog)

## Artículos relacionados

- [How I didn’t know how powerful and fast hashtables are](/es/blog/how-i-didnt-know-how-powerful-and-fast-hashtables-are/)
- [PowerShell – Few tricks about HashTables and Arrays I wish I knew when I started](/es/blog/powershell-few-tricks-about-hashtable-and-array-i-wish-i-knew-when-i-started/)
- [Check an API write after a PowerShell timeout](/es/blog/verify-uncertain-api-outcomes-powershell/)

<!-- PowerForge markdown artifact sha256:9224139A0F24C4FCDD07EB6DC28761231434BD134AE09C9B87C33F5538FE69C1 -->
