Advantages of a class-based DSC resource

So, how does having PowerShell classes benefit us with DSC resources? A PowerShell class defines both the schema and implementation of the DSC resource in the same file, greatly simplifying the authoring and use of DSC resources. Instead of the verbose folder structure we covered in the Creating PowerShell custom DSC resources in C# section, we have a single class that handles everything for us.

PowerShell MOF-based DSC resources require a specific folder structure and many files in order to work correctly. There is a lot of boilerplate code and repetition in declaring the properties and functions in order to make things work. The separate MOF schema file has to be kept in sync with the PowerShell module file implementing the Get, Set, and Test-TargetResource functions, which means manual human intervention. This is an error-prone process that is easily forgotten about when trying to make a DSC resource work.

Perhaps the easiest to overlook but most important part of a class-based DSC resource is the type safety provided. Type safety is a programming term that means a certain object, method, or property can only ever be the thing we assigned it. The methods and properties of a DSC class only return the information we expect, which returns runtime errors due to programming mistakes.

In PowerShell V4, there was no way to directly invoke the Get-TargetResource functions using DSC against a target node yourself, so the function had little utility in interactive use. In V4, it wasn't used internally by the DSC engine as much as it is in V5, so there were not very many people who bothered to implement the function.

Instead, they declared the function and had it return an empty hash. In PowerShell V5, you can directly invoke the Get-TargetResource function using Invoke-DscResource, which brings a lot of utility and purpose to this function. It is assumed that this function will really shine when there is a reporting feature to DSC. Currently, there isn't a way to report on the current state of target nodes using DSC. This information is stored after a DSC run is performed on a target node.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset