How to Create Elegant PowerShell Custom Objects In Code |
![]() |
![]() |
PowerShell |
Written by Darwin Sanoy |
Tuesday, November 12, 2013 9:20pm |
PowerShell custom objects are really the way to go for handling complex data in a script. Recently I had a need to create a set of custom objects in script code, but all the samples Google offered were convoluted. Clearly it was time to evolve the existing solutions into something more elegant. The result is code that is easy to understand for the beginner and a breath of fresh air for the veteran.
Elegance is not primarily about visual appeal, but rather about how simplicity of form facilitates ease of understanding and ease of use. Here are some of the things that I wanted in the solution (and simultaneously didn't like in the solutions I was able to find on the Net):
Below is the solution which fits the above design criteria: $Animals = @()P.S. Keep in mind that you can also store object data in CSV files and load it, so there is no "object creation" at all in your code. In this case I didn't want to use CSVs because: [a] I didn't want a dependency on additional files, [b] many times there would be only a single instance of the object, making the requirement for a file over kill and [c] since the object properties can contain special characters, it seemed like the character escaping might prove time consuming to store it in a file. |