Thursday, July 26, 2012

Creating Custom Objects

PowerShell is all about being object-oriented.  Once I learned how to create custom objects, then I really started having fun.  One can add custom properties to either a "blank" object or an existing object (which is cooler). 

To do so, either start with the existing object or a new-object system.object.  Then pipe it to add-member.  Add-member takes a -membertype, then the -name of the property, and finally  the -value.  

The top-three types that I use are as follows: 

  • noteproperty for a "static" value; the value is whatever, can be in parentheses
  • scriptproperty for a "dynamic" value, a code block; use $this. to reference the object
  • aliasproperty for another name for an existing property; the value is just the name of the existing property

I have had much success with add-member in my scripting. I cannot explain it all here, but I hope it whets your appetite!  Remember to use get-help add-member -detailed.

No comments:

Post a Comment