Part 2 – The Troika : PowerShell, YAML and PowerShell Classes

In the last post The Troika : PowerShell, YAML and PowerShell Classes, we took YAML, converted it to PowerShell objects and then used PowerShell v5.0 to cast it to a class. This gave us runtime checking to see if we fat fingered entries in the YAML. This required very little coding, just some simple scaffold setup.

Once you do this, you’re a couple of steps from even more capability.

Note: Notice that using PowerShell v5.0 classes to do this work gives you intellisense in the console and editors.

Defaults and Types

In this example, the YAML has two Purchasers, and we left out Jane’s Age. When we convert, cast and print it, is shows up blank.

Prints

Lets set the type the $Age property in the Purchaser class to int.

Now, when we covert and cast, Jane’s age is now 0.

Prints

There’s another benfit to typing $Age. What if in the YAML we type a string for Jane’s age?

PowerShell handles checking the type and reporting a very useful error.

Doing Defaults

Going back the PowerShell class, you can set defaults for properties not defined in the YAML (Jane’s Age) and introduce new ones.

Note: Adding $DateCreated to the Purchaser class now makes it legal to use and overridden from the YAML.

Prints

Next steps

Now we’ve seen how we can convert YAML from a string (or file) into PowerShell and have a simple way to catch errors, correctly type the data, create defaults and easily introduce new properties.

In upcoming posts we’ll look at how to validate the YAML, for example, what if certain properties are required but not set?

One thought on “Part 2 – The Troika : PowerShell, YAML and PowerShell Classes

Leave a Reply

Your email address will not be published. Required fields are marked *