Introducing PowerYaml

written by Scott Muc on Sunday, May 30 2010

I'm currently working on a project where we will be incorporating a lot of powershell. The scripts rely heavily on some sort of contextual configuration. Not wanting to introduce any more XML into the mix we started exploring YAML as the format for our configurations.

I didn't have to research very long to find that YAML does not have a lot of support in the .Net/PoSH world. There's no Powershell modules to be found and there seems to be only 3 .Net libraries out there:

Actually that last one is the hardest to find and it's the best, and the one I ended up using. Since Powershell doesn't have anything good to parse YAML with, I've elected to hook into the DLLs of the project and use it that way.

Here's a sample YAML document that I'm using for testing:

# This is a sample yaml file
parent: 
  child:
    a: a value
    b: b value
    c: c value
  child2: 
    key4: value 4
    key5: value 5

Our specific use case is that I just want to navigate to a certain node and return a name value collection (aka hash). Obviously this code won't handle all situations but for what we need, it's a start. After a few days of mucking around I ended up creating the following module that exposes one function:

Get-YamlNameValues is fairly straightforward. The -file parameter is required and needs to be a reference to a YAML file. The -ypath (thanks David Morgantini for that name) parameter is a list of node key names that are used to navigate to the node that I want the collection of. Think of it as a simple XPath like query for Yaml.

The following is an example usage:

> Import-Module YamlConfiguration.psm1
> $yaml = Resolve-Path .\sample.yml
> Get-YamlNameValues -file $yaml -ypath "parent", "child"

Will return the name-value collection that are children of the "child" node:

Name                           Value
----                           -----
a                              a value
b                              b value
c                              c value

Here's the module that performs all the magic. Most of the code mainly wraps the logic involved in opening a YamlStream and one little function that converts a list of YamlNode objects into values in a hash.

Similar Posts

  1. Unit Testing Domain Persistence With NDbUnit, NHibernate and SQLite
  2. My Developer Resolutions For 2010
  3. Getting My Build and Release On

Post a comment

Options:

Size

Colors