Powershell Quick Tip - Object Properties

I ran into a really quick and easy way to add/remove properties from powershell objects or arrays of objects, and wanted to share it. Basically, you just pipe an object into itself while selecting the all of the properties you want, even if they don't exist. Let's have a look...

First, make a new object with a Name property.

$ExampleObject = New-Object psobject -Property @{Name="Chris"}

Which when output to the console, will show you the standard format of property:value. Now lets assume you want to add the alias and FavoriteColor properties to this object, and this is where PowerShell really shines. Just pipe Select-Object, with all of the desired properties, into your object and voila!

$ExampleObject = $ExampleObject | Select-Object Name,alias,FavoriteColor

You now have an object with the propertys of Name, alias, and FavoriteColor. You can remove a property just as easily by just not including it in the Select-Object statement. Best of all, this works if you have an array of objects as well, by adding/removing the properties to every object in the array. I will be using this in my next post to do just that.

Tutorial Tags: