Automatic variables in Desired State Configuration

When you read through the DSC documentation at http://go.microsoft.com/fwlink/?LinkId=311940 , you learn that there are three automatic variables available to your DSC configuration code: $ConfigurationData , $AllNodes, and $Node.

There are actually six automatic DSC variables. Not documented (and arguably less useful), you also have variables named $MyTypeName, $SelectedNodes, and $NodeName.

$MyTypeName will be the name of the configuration (or composite configuration) that is active at any given time. This can perhaps be useful if you’ve placed some common code into a library or function that is used from multiple DSC configurations, and want to use that configuration name in a log file or error message.

$SelectedNodes and $NodeName, like $Node, are available inside a node{} block. $NodeName is the same as $Node.NodeName, and is a minor convenience. As you probably know, the body of the node{} block is essentially like a body of a ForEach loop, where $Node / $NodeName are associated with the node in the current iteration of the loop. The $SelectedNodes variable, on the other hand, is the entire array that was passed to the Node command. For example, in (node $AllNodes.Where({$_.SomeFilterCondition}).NodeName { }), inside the body, the $SelectedNodes variable will contain the same hash tables as $AllNodes.Where({$_.SomeFilterCondition}) . I can’t come up with a situation where having access to this information would be useful, off the top of my head, but if you have some sort of logic where it’s helpful to know things about the other nodes in the “loop”, you can use $SelectedNodes to get at that information.

Here’s some example code that you can run to display the values in these variables. I also threw in a demonstration of the (NodeName = ‘*’) case, which allows you to define a global property for all nodes (which can optionally be overridden on the individual nodes.) This is all built-in DSC functionality, and doesn’t require any external modules.

Advertisements

About Dave Wyatt

Microsoft MVP (PowerShell), IT professional.
This entry was posted in PowerShell and tagged . Bookmark the permalink.

2 Responses to Automatic variables in Desired State Configuration

  1. Brian says:

    Nice! I look forward to the day when these are better documented (officially).

    Like

  2. I bet $SelectedNodes can be useful with cross computer synchronization in WMF 5.0.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s