Author Posts

May 10, 2018 at 11:28 pm

Creating custom objects or even extending existing objects is pretty easy in PowerShell, but custom objects are harder to deal with in the pipeline and extending existing objects doesn't seem like a good option when writing modules.

For example, let's say I want to do more with the Get-Services cmdlet (BaseType = System.ComponentModel.Component). I can jump through a few hoops to create a custom object (call it Get-MyServices), put some of the same properties / methods into my object, and then create some new properties / methods. That is all well and good, until I want to use Get-MyServices in a pipeline in exactly the same way I would the native Get-Services cmdlet. I almost always also find that there is 1 or 2 other properties of the original object that I didn't include that I later need.

I'm pretty sure I can't create an object of type System.ComponentModel.Component (at least not natively in PowerShell), so is there a way to "clone" an existing object, get all of the goodness of it, extend it how I see fit, and know that when used in the pipeline, it will work exactly in the same way as its original?

If there's another way to accomplish the same objective, I'm open to anything. I'm just trying to get the extensibility promised by OOP. Thanks.

May 12, 2018 at 2:53 pm

It might be more helpful to give a coding example that shows the problem.

May 13, 2018 at 3:53 am

You can create a wrapper function for Get-Service which basically interacts with Get-Service directly, and tacks on additional properties to the regular objects that it gives using Add-Member or Select-Object's calculated properties. I would suggest including a PSTypeName as one of these additional properties to make it clear what you're doing at a glance.

Check out Get-Command mkdir | Select-Object -Expand Definition for a basic example of how to construct a proper wrapper function.