Wednesday, March 04, 2015

Generate a DSC Property from an Enum

Just a quick snippet to share for generating part of a DSC schema.  If the property you’re modeling is an enum then you can lock down the MOF schema by specifying the valid values.  A benefit here is that the user of your resource will get intellisense in PowerShell ISE for your resource property values, and will also fail a lot earlier (probably at authoring-time instead of waiting for the LCM to find the problem).

The only tricks here are really:

  • using the GetEnumNames() method to get at the valid names
  • using an array of strings to hold those items
  • joining the array into a single string with the –join operator
  • escaping the curly braces so that the –F operator will work

Here’s the snippet:



Generate a DSC propery with valueMap item from an enum


Something like this:


[Write, ValueMap{"foo","bar","baz"}, Values{"foo","bar","baz"}] String PropertyName;




### Create an array of quoted strings from the Enum names

$valueMapStrings = @()

[Microsoft.IdentityManagement.PowerShell.ObjectModel.ComparisonOperator].GetEnumNames() | ForEach-Object {

    $valueMapStrings += '"{0}"' -F $_



### Put the array of enum names into the DSC property definition

'[Write, ValueMap{{{0}}}, Values{{{0}}}] String ComparisonOperator;' -F ($valueMapStrings -join ',') | clip


No comments: