Saturday, July 27, 2024
HomePowershellUnlocking PowerShell Magic: Totally different Strategy to Creating 'Empty' PSCustomObjects

Unlocking PowerShell Magic: Totally different Strategy to Creating ‘Empty’ PSCustomObjects


This is a snippet code that exhibits easy methods to create a customized object utilizing OrderedDictionary and conversion course of

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

It’s also possible to create customized objects dynamically utilizing the same strategy to what Christian proposed.

$propertyDefinitions = @{
    Customers   = @(
        "FirstName", "LastName", "UserName", "Title", "Division",
        "StreetAddress", "Metropolis", "State", "PostalCode", "Nation",
        "PhoneNumber", "MobilePhone", "UsageLocation", "License"
    )
    Teams  = @(
        "DisplayName", "PrimarySMTP", "Description", "Proprietor", "Kind"
    )
    JobRole = @(
        "DisplayName", "PrimarySMTP", "Description", "Kind"
    )
}


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

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

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

OrderedDictionary moreover gives the flexibility to create an object with some information after which append information on the fly in your script. This implies, for instance, you could possibly create a dictionary first in the beginning of the script, and through the entire run of the script, you could possibly append information to it with out ever pre-creating it within the first place, to lastly convert it to a customized object.

$Properties="Title", 'Division', 'State'
$CustomObject1 = [ordered] @{
    Identify="John"
    Age  = 30
    Metropolis = 'New York'
}
foreach ($P in $Properties) {
    $CustomObject1[$P] = $null
}
[pscustomobject] $CustomObject1

In an extended script you could possibly do

$CustomObject1 = [ordered] @{
    Identify="John"
    Age  = 30
    Metropolis = 'New York'
}
<#
Do plenty of code right here
#>
$CustomObject1['Address'] = 'New Worth'
<#
Extra code right here
#>
$CustomObject1['State'] = 'New Worth 2'
# Convert to PSCustomObject
[pscustomobject] $CustomObject1

One other good thing about utilizing OrderedDictionary is that you may add to it inside different capabilities with out ever having to destroy the article, overwrite it, and even figuring out beforehand what it’ll appear to be.

operate Add-Values {
    [CmdletBinding()]
    param(
        [System.Collections.IDictionary] $Dictionary,
        [string] $Key,
        [object] $Worth
    )
    $Dictionary[$Key] = $Worth
}

$CustomObject1 = [ordered] @{
    Identify="John"
    Age  = 30
    Metropolis = 'New York'
}
<#
Do plenty of code right here
#>
$CustomObject1['Address'] = 'New Worth'
<#
Extra code right here
#>
$CustomObject1['State'] = 'New Worth 2'
Add-Values -Dictionary $CustomObject1 -Key 'ZipCode' -Worth 'New Worth 3'
<#
Much more code
#>
Add-Values -Dictionary $CustomObject1 -Key 'EmployeeID' -Worth 'New Worth 4'

# Convert to PSCustomObject
[pscustomobject] $CustomObject1

I hope this brief weblog put up will provide help to determine between my and Christian options. Each options have their very own strengths, and relying on who likes what, chances are you’ll find yourself utilizing one or the opposite. Christian answer relies on PowerShell 2.0 when it was the one solution to create PSCustomObject.

# what Christian proposes
$customObject1 = [PSCustomObject]@{} # this line is definitely not wanted
$customObject1 | Choose-Object -Property $PropertyNames

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

I used to be curious if there’s any efficiency distinction between these two options. Utilizing a easy Measure-Command offers us the reply.

$PropertyNames = @(
    "FirstName", "LastName", "UserName", "Title", "Division",
    "StreetAddress", "Metropolis", "State", "PostalCode", "Nation",
    "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++)  Choose-Object -Property $PropertyNames
    
}

In PowerShell 5.1, over 100k iterations, it takes about 1 second much less for my strategy than utilizing Choose-Object.

In PowerShell 7, the distinction is about 500ms which isn’t noticeable.

To summarize, each options work; I consider OrderedDictionary conversion has extra execs and, not less than for me, is less complicated to learn and perceive how all the things occurs. Only a factor of word – you could possibly additionally use Hashtable as an alternative of OrderedDictionary, however then the order of properties shouldn’t be assured, which can or could not matter to you. Ultimately, the selection is at all times yours. Take pleasure in

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments