In JavaScript you can use the spread operator to clone an object and then extend its properties. Is there an equivalent operation in powershell to accomplish this?
JS example:
const b = {
...a,
newProp: 'abc'
}
There are various discussions on StackOverflow (for example) about cloning objects. I've not revisited them in a while, however absent a .Clone()
method on the object itself these approaches often seem to only clone shallow. Meaning deeply nested properties, and more complex properties like arrays and/or other objects aren't easily cloned. It is however easy to extend objects in PowerShell. Select-Object
has such a capability through use of calculated properties. Select-Object
will output a new object of type [PSCustomObject]
. You can use Add-Member
to add properties while maintaining the formal typing of the original object, however this add to the object it's passed, you may have to play around to achieve the cloning aspect of your question.
Select-Object
Add-Member
Possible Example:
# Get an object to work with:
$OriginalObject = (Get-Process)[0]
$NewObject =
$OriginalObject |
Select-Object *,@{Name = 'Date'; Expression = { Get-Date } }
This adds a date property the value of which is the result of the expression. Admittedly not that useful here, but it's just to demonstrate the point. The *
carries forward the existing properties resulting in something close to a clone of the original plus the new property. You can put anything you want in the expression and add as many properties as you want. So you can see there's a lot of utility behind calculated properties. You can also tailor the object further by naming actual properties of the source object instead of the wildcard (*
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With