Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a spread operator equivalent in Powershell?

Tags:

powershell

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'
}
like image 583
Jared Beach Avatar asked Sep 05 '25 03:09

Jared Beach


1 Answers

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 (*).

like image 184
Steven Avatar answered Sep 09 '25 18:09

Steven