How to Create Elegant PowerShell Custom Objects In Code Print E-mail
Written by Darwin Sanoy   
Tuesday, November 12, 2013 8: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):

  • The syntax should be very clean.
  • Easily understood by new scripters who haven't worked much with custom objects.
  • It should be easy to use for a single instance object.
  • It should be easy to add instances (preferrably by copying a code bock.)
  • It should allow documentation via comments.
  • It would be preferrable if there was no "enclosing" syntax that can be forgotten or clipped.

Below is the solution which fits the above design criteria:

$Animals = @()

$Animals += New-Object PSObject -Property @{

   Name        =  "Dog"
Domestic   =  $True
   Disposition =  "Happy Go Lucky"
Fetches = $True
$Animals += New-Object PSObject -Property @{
  Name         =  "Cat"
# Insert comments where helpful
Domestic   =  $True
  Disposition =  "Sultry" # options "Sultry", "Sad", "Angry"
Fetches = $False
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.